sum_number_helper.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # -*- coding: utf-8 -*-
  2. from odoo.exceptions import ValidationError
  3. class SumNumberHelper(object):
  4. def __init__(self):
  5. self.dic = {}
  6. def add(self, key, number):
  7. if not number:
  8. number = 0
  9. if not key:
  10. key = '__none__'
  11. if key in self.dic:
  12. value = self.dic[key]
  13. self.dic[key] = value + number
  14. else:
  15. self.dic[key] = number
  16. def get(self, key):
  17. if not key:
  18. key = '__none__'
  19. if key not in self.dic:
  20. return 0
  21. return self.dic[key]
  22. class SumNumberConditionHelper(object):
  23. def __init__(self):
  24. self.dic = {}
  25. def add(self, key, unit, number):
  26. if not number:
  27. number = 0
  28. if not key:
  29. key = '__none__'
  30. if key in self.dic and unit == self.dic[key][1]:
  31. value = self.dic[key][0]
  32. self.dic[key][0] = value + number
  33. else:
  34. self.dic[key] = [number, unit if unit else '']
  35. def get(self, key, unit):
  36. if not key:
  37. key = '__none__'
  38. if key not in self.dic:
  39. return 0
  40. if self.dic[key][1] == unit:
  41. print self.dic[key][0]
  42. return self.dic[key][0]
  43. # 合计相同个数的数量。
  44. # 例如:
  45. # a = [m,1,2,3,4]
  46. # b = [m,5,6,7,8]
  47. # c = [n,11,12,13,14]
  48. # 操作:按第1列分组,对其余列求和
  49. # 则:结果为{m:[6,8,10,12], n:[11,12,13,14]}
  50. # =====用法:=====
  51. # helper = SumNumbersHelper(4)
  52. # helper.add_numbers(m, [1,2,3,4])
  53. # helper.add_numbers(m, [5,6,7,8])
  54. # helper.add_numbers(n, [11,12,13,14])
  55. # 得到m的结果:helper.get(m)
  56. # 得到n的结果:helper.get(n)
  57. class SumNumbersHelper(object):
  58. def __init__(self, number_count):
  59. self.dic = {}
  60. self.number_count = number_count
  61. def add_numbers(self, key, numbers):
  62. if not numbers:
  63. raise ValidationError(u'第2个参数不合法,应该为数组,元素个数为:' + str(self.number_count))
  64. if len(numbers) != self.number_count:
  65. raise ValidationError(u'第2个参数个数不对,应该为' + str(self.number_count))
  66. if not key:
  67. key = '__none__'
  68. if key in self.dic:
  69. value = self.dic[key]
  70. self.dic[key] = self._sum(value, list(numbers))
  71. else:
  72. self.dic[key] = list(numbers)
  73. def get(self, key):
  74. if not key:
  75. key = '__none__'
  76. if key not in self.dic:
  77. return 0
  78. return self.dic[key]
  79. def _sum(self, arr1, arr2):
  80. for i in range(self.number_count):
  81. arr1[i] += arr2[i]
  82. return arr1