Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
oop solution in Clear category for Can Balance by marcopunteri
from typing import Iterable
class Balance:
def __init__(self,weights):
self._weights = weights
self._positions = list(range(-(len(self._weights)//2),1+len(self._weights)//2))
@property
def fulcrum(self):
return self._positions.index(0)
@property
def balance(self):
return sum([pos*weight for pos, weight in zip(self._positions,self._weights)])
def move_fulcrum(self, direction):
if direction > 0:
self._positions.pop()
self._positions.insert(0,self._positions[0]-1)
elif direction < 0:
self._positions.pop(0)
self._positions.append(self._positions[-1]+1)
def can_balance(weights: Iterable) -> int:
b = Balance(weights)
last_value = None
while True:
if b.balance == 0:
break
if not last_value:
last_value = b.balance
b.move_fulcrum(b.balance)
else:
if 0 < b.balance < last_value or last_value < b.balance < 0:
last_value = b.balance
b.move_fulcrum(b.balance)
else:
break
return b.fulcrum if b.balance == 0 else -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!")
Nov. 8, 2021
Comments: