12
返回列表 发新帖
楼主: nothingtrouble
跳转到指定楼层
上一主题 下一主题
收起左侧

Square的店面

🔗
biubiugo 2017-1-8 15:58:57 | 只看该作者
全局:
求问楼主是哪个岗位呀
回复

使用道具 举报

🔗
johnnywsd 2017-1-24 15:50:56 | 只看该作者
全局:
  1. from collections import defaultdict


  2. class Solution:
  3.     def get_balance(self, transations):
  4.         balance_dct = defaultdict(int)
  5.         for amount, payer, payees in transations:
  6.             balance_dct[payer] -= amount
  7.             amount_payee = float(amount) / len(payees)
  8.             for payee in payees:
  9.                 balance_dct[payee] += amount_payee
  10.         return balance_dct

  11.     def get_due(self, balance_dct):
  12.         if sum(balance_dct.values()) != 0:
  13.             raise Exception('Not balance')
  14.         debets = sorted([it for it in balance_dct.items() if it[1] > 0], key=lambda x: x[1])
  15.         credit = sorted([it for it in balance_dct.items() if it[1] < 0], key=lambda x: -x[1])
  16.         give_dct = defaultdict(list)
  17.         while debets and credit:
  18.             debet_user, debet_val = debets.pop()
  19.             credit_user, credit_val = credit.pop()
  20.             bal = debet_val + credit_val
  21.             if bal > 0:
  22.                 debets.append((debet_user, bal))
  23.             elif bal < 0:
  24.                 credit.append((credit_user, bal))

  25.             give_dct[debet_user].append((credit_user, min(debet_val, -credit_val)))
  26.         return give_dct
复制代码

  1. import unittest
  2. from solution import Solution

  3. class Tests(unittest.TestCase):
  4.     def test_1(self):
  5.         sol = Solution()
  6.         transations = [(12, 'A', ('A', 'B', 'C')), (10, 'B', ('A', 'B'))]
  7.         res = sol.get_balance(transations)
  8.         print res

  9.     def test_2(self):
  10.         sol = Solution()
  11.         transations = [(12, 'A', ('A', 'B', 'C')), (10, 'B', ('A', 'B'))]
  12.         balance_dct = sol.get_balance(transations)
  13.         res = sol.get_due(balance_dct)
  14.         print res

  15. if __name__ == '__main__':
  16.     unittest.main(verbosity=2)
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表