Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
analytical solution in Clear category for Can Balance by juestr
from typing import Iterable
def can_balance(weights: Iterable) -> int:
# torque == sum((i - p) * w for i, w in enumerate(weights)) == 0
# ==> sum(i*w_i) - sum(p*w_i) == 0
# ==> sum(i*w_i) - p*sum(w_i) == 0
# ==> p == sum(i*w_i)/sum(w_i)
p = sum(i*w for i, w in enumerate(weights)) / sum(weights)
return int(p) if int(p) == p else -1
April 20, 2019
Comments: