Created
November 15, 2011 23:53
-
-
Save teffalump/1368799 to your computer and use it in GitHub Desktop.
basically, you have a series of bills that people have paid -- the question is, who owes whom? this script calculates this, just needs all the receipts and the weights. the weights are, for example, if person x should only pay .5 equal split, weight = .5
This file contains 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
#!/usr/bin/python3 | |
#Split bills according to payment weights | |
#how much each person paid and weight of person | |
amts={} | |
while True: | |
label=input("\nperson: ") | |
if label == "": | |
break | |
else: | |
amt=0 | |
while True: | |
item = input("\t" + label + " receipt paid: ") | |
if item == '': | |
break | |
else: | |
amt+=float(item) | |
amts[label]={"paid":amt} | |
rule = input("\tweight: ") | |
if rule == '': | |
amts[label]["weight"]=1 | |
else: | |
amts[label]["weight"]=float(rule) | |
#calculate difference from what person should pay | |
#DEBUG for i in amts.items(): print(i) | |
total = sum([x["paid"] for x in amts.values()]) | |
total_weights=sum([x["weight"] for x in amts.values()]) | |
equal_share_amt = (1 / total_weights) * total | |
for person in amts.items(): | |
diff = person[1]["paid"] - (person[1]["weight"] * equal_share_amt) | |
amts[person[0]]["diff"]=diff | |
#distinguish debts and surpluses | |
diffs = [[x[0],x[1]["diff"]] for x in amts.items()] | |
s = sorted([x for x in diffs if x[1] > 0], key=lambda y: y[1]) | |
d = sorted([[x[0], abs(x[1])] for x in diffs if x[1] < 0], key=lambda p: p[1]) | |
#what people owe generally | |
for person in diffs: | |
if person[1] < 1: | |
print("\n{0} owes {1}".format(person[0], round(abs(person[1]),2))) | |
#what people owe to each person | |
#it should be noted that this employs a way to go about this | |
#...biggest debtors pay to biggest surplusees, recalculate, etc.... | |
#however, one can pay off the debts however one wants | |
while True: | |
if not d or not s: break | |
else: | |
#surplus > debt | |
if s[-1][1] > d[-1][1]: | |
print("\t\t{0} owes {1} {2} dollars".format(d[-1][0], s[-1][0], round(d[-1][1],2))) | |
s[-1][1] = s[-1][1] - d[-1][1] | |
del d[-1] | |
#surplus == debt | |
elif s[-1][1] == d[-1][1]: | |
print("\t\t{0} owes {1} {2} dollars".format(d[-1][0], s[-1][0], round(d[-1][1],2))) | |
del d[-1] | |
del s[-1] | |
#surplus < debt | |
else: | |
print("\t\t{0} owes {1} {2} dollars".format(d[-1][0], s[-1][0], round(s[-1][1],2))) | |
d[-1][1] = d[-1][1] - s[-1][1] | |
del s[-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment