Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Can Balance by Alexey.K.
from typing import Iterable
def multisum(l):
return sum([l[::-1][k] * (k+1) for k in range(len(l))])
def can_balance(weights: Iterable) -> int:
l = []
r = []
for s in range(len(weights)-1):
ls = multisum(l)
rs = multisum(r)
if ls <= rs:
l += [weights.pop(0)]
else:
r += [weights.pop(-1)]
ls = multisum(l)
rs = multisum(r)
if ls == rs:
return len(l)
else:
return -1
if __name__ == '__main__':
print("Example:")
print(can_balance([6, 1, 10, 5, 4]))
# These "asserts" are used for self-checking and not for an auto-testing
assert can_balance([6, 1, 10, 5, 4]) == 2
assert can_balance([10, 3, 3, 2, 1]) == 1
assert can_balance([7, 3, 4, 2, 9, 7, 4]) == -1
assert can_balance([42]) == 0
print("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 1, 2021
Comments: