Last active
October 30, 2016 20:55
-
-
Save rmeertens/e63451975ba85a65cd14287b0676c020 to your computer and use it in GitHub Desktop.
Wie betaalt wat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import operator # For sorting my dictionary | |
bills = {"Kim":392.08,"Peter":71.81,"Mike":48.09,"Roland":5.91,"Yorick":0.0,"Elvira":-74.37,"Lisette":-103.22,"Robert":-340.30} | |
transactions = 0 | |
while sorted(bills.items(), key=operator.itemgetter(1),reverse=True)[0][1]>0.001: | |
transactions+=1 | |
sorted_bills = sorted(bills.items(), key=operator.itemgetter(1),reverse=True) | |
diff_highest_lowest = sorted_bills[0][1]+sorted_bills[-1][1] # Note that array[-1] is the last element of an array (for us: lowest value) | |
if diff_highest_lowest > 0: # In this case the lowest amount can't fill the highest amount | |
print(sorted_bills[-1][0] + " pays " + sorted_bills[0][0]+ ": " + str(abs(sorted_bills[-1][1]))) # Pay everything you have | |
bills[sorted_bills[-1][0]]=0 # The lowest bill is done paying! | |
bills[sorted_bills[0][0]] = diff_highest_lowest # The person with the most amount of money still needs to receive money | |
else: # The highest amount gets completely paid off. | |
print(sorted_bills[-1][0] + " pays " + sorted_bills[0][0]+ ": " + str(abs(sorted_bills[0][1]))) | |
bills[sorted_bills[-1][0]]=diff_highest_lowest # The lowest person still has to pay | |
bills[sorted_bills[0][0]]=0 # The richest person got all of his money | |
print("Amount of transactions: " + str(transactions)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment