Skip to content

Instantly share code, notes, and snippets.

@raymonstah
Last active August 29, 2015 14:20
Show Gist options
  • Save raymonstah/7fde469db6820d3f9f3d to your computer and use it in GitHub Desktop.
Save raymonstah/7fde469db6820d3f9f3d to your computer and use it in GitHub Desktop.
Got a total of who payed what and need to break it down to see who owes who? Use me!
# Raymond Ho
# May 5, 2015
# Note: Run me through the terminal.
# Sublime Text 2 won't successfully build b/c of Unicode errors.
import csv
import sys
def parseData(data, colPrice=1, colPerson=5, nameA='Alice', nameB='Bob'):
'''
data = A list containing the CSV data
colPrice = The column that the prices are stored in
colPerson = The column that stores who payed
nameA = The name of person A
nameB = The name of person B
This function will calculate how much personA owes personB or vice versa.
'''
personA, personB = [], []
totalA, totalB = 0, 0
for entry in data:
try:
if entry[colPerson] == nameA:
personA.append(entry)
totalA += float(entry[colPrice])
elif entry[colPerson] == nameB:
personB.append(entry)
totalB += float(entry[colPrice])
else:
print('Name not recognized: ' + entry[colPerson])
# return
except IndexError: # Blank line.
continue
difference = (totalA - totalB) / 2
if totalA > totalB:
print (("%s owes %s %.2f dollars.") % (nameB, nameA, difference))
else:
print (("%s owes %s %.2f dollars.") % (nameA, nameB, -difference))
def main():
data = []
with open(sys.argv[1]) as csvfile:
expenses = csv.reader(csvfile)
for row in expenses:
data.append(row)
parseData(data)
if __name__ == '__main__':
if len(sys.argv) == 2:
main()
else:
print("Please specify a .csv file.")
What? $ Date? Paid? Notes Payed With?
Safeway 35.31 Apr 3, 2015 Bob
Kims 17.91 Apr 3, 2015 Alice
PGE 17.28 Apr 6, 2015 Alice
Safeway 64.37 Apr 10, 2015 Bob
Safeway 33.44 Apr 14, 2015 Alice
Noah’s Bagel 8.99 Apr 14, 2015 Alice
Safeway 36.47 Apr 19, 2015 Alice
Comcast 59.98 Apr 23, 2015 Alice
Safeway 28.79 Apr 27, 2015 Bob
Rent 1117.19 May 2, 2015 Checkpoint Bob
Alice owes Bob 535.80 dollars.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment