新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-11-7
- 最后登录
- 1970-1-1
|
- from collections import defaultdict
- class Solution:
- def get_balance(self, transations):
- balance_dct = defaultdict(int)
- for amount, payer, payees in transations:
- balance_dct[payer] -= amount
- amount_payee = float(amount) / len(payees)
- for payee in payees:
- balance_dct[payee] += amount_payee
- return balance_dct
- def get_due(self, balance_dct):
- if sum(balance_dct.values()) != 0:
- raise Exception('Not balance')
- debets = sorted([it for it in balance_dct.items() if it[1] > 0], key=lambda x: x[1])
- credit = sorted([it for it in balance_dct.items() if it[1] < 0], key=lambda x: -x[1])
- give_dct = defaultdict(list)
- while debets and credit:
- debet_user, debet_val = debets.pop()
- credit_user, credit_val = credit.pop()
- bal = debet_val + credit_val
- if bal > 0:
- debets.append((debet_user, bal))
- elif bal < 0:
- credit.append((credit_user, bal))
- give_dct[debet_user].append((credit_user, min(debet_val, -credit_val)))
- return give_dct
复制代码
- import unittest
- from solution import Solution
- class Tests(unittest.TestCase):
- def test_1(self):
- sol = Solution()
- transations = [(12, 'A', ('A', 'B', 'C')), (10, 'B', ('A', 'B'))]
- res = sol.get_balance(transations)
- print res
- def test_2(self):
- sol = Solution()
- transations = [(12, 'A', ('A', 'B', 'C')), (10, 'B', ('A', 'B'))]
- balance_dct = sol.get_balance(transations)
- res = sol.get_due(balance_dct)
- print res
- if __name__ == '__main__':
- unittest.main(verbosity=2)
复制代码 |
|