Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Not only lists are iterable solution in Clear category for Can Balance by tom-tom
from itertools import starmap
from operator import mul
from typing import Iterable
def can_balance(weights: Iterable) -> int:
weights = list(weights)
quotient, remainder = divmod(sum(starmap(mul, enumerate(weights))), sum(weights))
return quotient if not remainder else -1
if __name__ == '__main__':
# check lists:
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
# check ranges:
assert can_balance(range(1, 4)) == -1
assert can_balance(range(1, 5)) == 2
# check generator function:
def my_iterable():
yield from (5, 2, 3, 1)
assert can_balance(my_iterable()) == 1
Dec. 14, 2018
Comments: