Skip to content

Instantly share code, notes, and snippets.

@ibarrajo
Created April 23, 2018 19:29
Show Gist options
  • Save ibarrajo/33241d666e0745fe2815d6277b69b785 to your computer and use it in GitHub Desktop.
Save ibarrajo/33241d666e0745fe2815d6277b69b785 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "'''\nSarah rents a car for the trip - she pays $400 for the car, which is used by Alice, John, \nBob and herself. Later in the trip, John went out and bought groceries for $100, \nwhich was used only by Alice and Bob.\n\nNow, the trip is over and everyone wants to get paid back what they are owed - \nprint out the list of transactions that would settle everyone's debts.\n\n\nledger = Ledger()\nledger.transaction('sarah', 400, [alice, john, bob, sarah])\nledger.transaction('john', 100, [alice, bob])\n\n'''\n\nclass Ledger():\n def __init__(self, accounts):\n self.accounts = [] \n self.transactions = []\n for a in accounts:\n self.addAccount(a)\n \n def addAccount(self, account):\n self.accounts.append(account)\n \n def transaction(self, payer, amount, beneficiaries):\n self.transactions.append({'payer': payer, 'amount': amount, 'beneficiaries': beneficiaries})\n \n def settle(self):\n balances = {}\n for account in self.accounts:\n balances[account] = 0\n \n for transaction in self.transactions:\n balances[transaction['payer']] += transaction['amount']\n \n owed = transaction['amount'] / len(transaction['beneficiaries'])\n for beneficiary in transaction['beneficiaries']:\n if beneficiary != transaction['payer']:\n print(\"{} owes {} ${:.2f}\".format(beneficiary, transaction['payer'], owed))\n \n \n \n \n \n \nledger = Ledger(['alice', 'john', 'bob', 'sarah'])\nledger.transaction('sarah', 400, ['alice', 'john', 'bob', 'sarah'])\n\nledger.transaction('john', 100, ['alice', 'bob'])\nledger.settle()\n \n\n\n\n\n\n\n",
"execution_count": 9,
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": "alice owes sarah $100.00\njohn owes sarah $100.00\nbob owes sarah $100.00\nalice owes john $50.00\nbob owes john $50.00\n"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "",
"execution_count": null,
"outputs": []
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python 3",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.6.4",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment