Created
May 9, 2022 20:19
-
-
Save les-peters/3ae395cd163585446abea59a960f82b5 to your computer and use it in GitHub Desktop.
Who Owes Money
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
question = """ | |
You went on a vacation with friends. Each of you paid for certain meals | |
on the trip for the group. Write a function that determines who owes | |
money to whom so that everyone pays equally. | |
Example: | |
let receipts = [ | |
{ name: 'Ximena', paid: 45 }, | |
{ name: 'Clara', paid: 130 }, | |
{ name: 'Ximena', paid: 100 }, | |
{ name: 'Cassidy', paid: 140 }, | |
{ name: 'Cassidy', paid: 76 }, | |
{ name: 'Clara', paid: 29 }, | |
{ name: 'Ximena', paid: 20 }, | |
] | |
$ whoOwes(receipts) | |
$ 'Clara owes Cassidy $21, Ximena owes Cassidy $15' | |
""" | |
def whoOwes(receipts): | |
sum = 0 | |
per_person = {} | |
for receipt in receipts: | |
if receipt['name'] not in per_person: | |
per_person[receipt['name']] = 0 | |
per_person[receipt['name']] = per_person[receipt['name']] + receipt['paid'] | |
sum = sum + receipt['paid'] | |
average = sum / len(per_person.keys()) | |
who_paid_most = list(sorted(per_person.items(), key=lambda item: item[1]))[-1][0] | |
for person in per_person.keys(): | |
if per_person[person] < average: | |
print(person, 'needs to pay', who_paid_most, '$' + str(average - per_person[person])) | |
receipts = [ | |
{ "name": "Ximena", "paid": 45 }, | |
{ "name": "Clara", "paid": 130 }, | |
{ "name": "Ximena", "paid": 100 }, | |
{ "name": "Cassidy", "paid": 140 }, | |
{ "name": "Cassidy", "paid": 76 }, | |
{ "name": "Clara", "paid": 29 }, | |
{ "name": "Ximena", "paid": 20 }, | |
] | |
whoOwes(receipts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment