raise Exception if no solution instead of infinite loop
This commit is contained in:
parent
9288c9dd56
commit
31e73d8179
1 changed files with 8 additions and 4 deletions
12
splitbill.py
12
splitbill.py
|
|
@ -30,10 +30,7 @@ def solve_greedily(
|
||||||
) -> dict[tuple[str, str], int]:
|
) -> dict[tuple[str, str], int]:
|
||||||
creditors, debitors = split_dict(balances, lambda k, v: v > 0)
|
creditors, debitors = split_dict(balances, lambda k, v: v > 0)
|
||||||
transactions = {}
|
transactions = {}
|
||||||
while not all(
|
for _ in range(len(balances)):
|
||||||
abs(value) <= tolerance
|
|
||||||
for value in chain(creditors.values(), debitors.values())
|
|
||||||
):
|
|
||||||
for debitor, debit_value in sorted(
|
for debitor, debit_value in sorted(
|
||||||
debitors.items(),
|
debitors.items(),
|
||||||
key=lambda x: x[1],
|
key=lambda x: x[1],
|
||||||
|
|
@ -53,6 +50,13 @@ def solve_greedily(
|
||||||
debitors[debitor] = sum_value
|
debitors[debitor] = sum_value
|
||||||
transactions[debitor, creditor] = credit_value
|
transactions[debitor, creditor] = credit_value
|
||||||
break
|
break
|
||||||
|
if all(
|
||||||
|
abs(value) <= tolerance
|
||||||
|
for value in chain(creditors.values(), debitors.values())
|
||||||
|
):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
raise ValueError("No solution within tolerance found")
|
||||||
return transactions
|
return transactions
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue