numbers_helper.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. from odoo.exceptions import ValidationError
  3. # 合计相同个数的数量。
  4. # 例如:
  5. # a = [m,1,2,3,4]
  6. # b = [m,5,6,7,8]
  7. # c = [n,11,12,13,14]
  8. # 操作:按第1列分组,第2列求最小值、第3列求最大值、第4列求和、第5列求平均值
  9. # 则:结果为{m:[1,6,10,6], n:[11,12,13,14]}
  10. # =====用法:=====todo: 求和、求最大、求最小已验证;求平均值是错误的.由于不支持求平均,因此最后一个数 *=* 不要理会 *=*
  11. # helper = NumbersHelper(4, {0:3,1:2,3:4}) # todo:由于不支持求平均,因此,去掉,3:4
  12. # helper.add_numbers(m, [1,2,3,4])
  13. # helper.add_numbers(m, [5,6,7,8])
  14. # helper.add_numbers(n, [11,12,13,14])
  15. # 得到m的结果:helper.get(m)
  16. # 得到n的结果:helper.get(n)
  17. class NumbersHelper(object):
  18. # number_operator:
  19. # key: index(要处理数字的序号,从0开始。没有时,value取1);
  20. # value:operator(sum:1(default),max:2,min:3) todo:average:4,的算法错误
  21. def __init__(self, number_count, number_operator):
  22. self.dic = {}
  23. self.number_count = number_count
  24. self.number_operator = number_operator
  25. def add_numbers(self, key, numbers):
  26. if not numbers:
  27. raise ValidationError(u'第2个参数不合法,应该为数组,元素个数为:' + str(self.number_count))
  28. if len(numbers) != self.number_count:
  29. raise ValidationError(u'第2个参数个数不对,应该为' + str(self.number_count))
  30. if not key:
  31. key = '__none__'
  32. if key in self.dic:
  33. value = self.dic[key]
  34. self.dic[key] = self._operate(value, list(numbers))
  35. else:
  36. self.dic[key] = list(numbers)
  37. def get(self, key):
  38. if not key:
  39. key = '__none__'
  40. if key not in self.dic:
  41. return 0
  42. return self.dic[key]
  43. def _operate(self, arr1, arr2):
  44. for i in range(self.number_count):
  45. if i in self.number_operator:
  46. if self.number_operator[i] == 1:
  47. arr1[i] += arr2[i]
  48. elif self.number_operator[i] == 2:
  49. if arr2[i] > arr1[i]:
  50. arr1[i] = arr2[i]
  51. elif self.number_operator[i] == 3:
  52. if arr2[i] < arr1[i]:
  53. arr1[i] = arr2[i]
  54. # elif self.number_operator[i] == 4: # todo:该算法是错误的
  55. # sum_with_current = arr1[i] * i + arr2[i]
  56. # arr1[i] = float(sum_with_current) / (i + 1)
  57. else:
  58. raise ValidationError(u'未处理的操作类型')
  59. else:
  60. arr1[i] += arr2[i]
  61. return arr1