Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second analytical, with exact integer math only solution in Clear category for Can Balance by juestr
from itertools import starmap
from operator import mul
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)
position, notexact = divmod(sum(starmap(mul, enumerate(weights))), sum(weights))
return -1 if notexact else position
April 22, 2019
Comments: