How can I change cash
inside the while_true function?
def all_average_cost(level_needs, cash):
"""Gets all with the exact same cost."""
cost = 0
def while_true():
if len(level_needs) == 0:
return False
cost = cash / len(level_needs)
for need in level_needs:
if cost >= (cost_item := need[1] * need[0].price):
cash -= cost_item # the problem is here *********
yield need
level_needs.remove(need)
yield from while_true()
return False
for iteration in while_true():
if iteration:
yield iteration
for i, need in enumerate(level_needs):
quantity = cost / need[0].price
if quantity >= need[1]:
quantity = need[1]
yield need[0], quantity
Small reproducible test:
def _test_self():
class Prod:
def __init__(self, price):
self.price = price
def __repr__(self):
return f"Prod(price={self.price})"
for a in all_average_cost([(Prod(50), 2), (Prod(100), 3)], 500):
print(a)
Should print:
(Prod(price=50), 2)
(Prod(price=100), 3)
I don't expect there to be a way.
Also, I'm just avoiding a double continue in yield from while_true()