1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- # -*- coding: utf-8 -*-
- from odoo.exceptions import ValidationError
- # 合计相同个数的数量。
- # 例如:
- # a = [m,1,2,3,4]
- # b = [m,5,6,7,8]
- # c = [n,11,12,13,14]
- # 操作:按第1列分组,第2列求最小值、第3列求最大值、第4列求和、第5列求平均值
- # 则:结果为{m:[1,6,10,6], n:[11,12,13,14]}
- # =====用法:=====todo: 求和、求最大、求最小已验证;求平均值是错误的.由于不支持求平均,因此最后一个数 *=* 不要理会 *=*
- # helper = NumbersHelper(4, {0:3,1:2,3:4}) # todo:由于不支持求平均,因此,去掉,3:4
- # helper.add_numbers(m, [1,2,3,4])
- # helper.add_numbers(m, [5,6,7,8])
- # helper.add_numbers(n, [11,12,13,14])
- # 得到m的结果:helper.get(m)
- # 得到n的结果:helper.get(n)
- class NumbersHelper(object):
- # number_operator:
- # key: index(要处理数字的序号,从0开始。没有时,value取1);
- # value:operator(sum:1(default),max:2,min:3) todo:average:4,的算法错误
- def __init__(self, number_count, number_operator):
- self.dic = {}
- self.number_count = number_count
- self.number_operator = number_operator
- def add_numbers(self, key, numbers):
- if not numbers:
- raise ValidationError(u'第2个参数不合法,应该为数组,元素个数为:' + str(self.number_count))
- if len(numbers) != self.number_count:
- raise ValidationError(u'第2个参数个数不对,应该为' + str(self.number_count))
- if not key:
- key = '__none__'
- if key in self.dic:
- value = self.dic[key]
- self.dic[key] = self._operate(value, list(numbers))
- else:
- self.dic[key] = list(numbers)
- def get(self, key):
- if not key:
- key = '__none__'
- if key not in self.dic:
- return 0
- return self.dic[key]
- def _operate(self, arr1, arr2):
- for i in range(self.number_count):
- if i in self.number_operator:
- if self.number_operator[i] == 1:
- arr1[i] += arr2[i]
- elif self.number_operator[i] == 2:
- if arr2[i] > arr1[i]:
- arr1[i] = arr2[i]
- elif self.number_operator[i] == 3:
- if arr2[i] < arr1[i]:
- arr1[i] = arr2[i]
- # elif self.number_operator[i] == 4: # todo:该算法是错误的
- # sum_with_current = arr1[i] * i + arr2[i]
- # arr1[i] = float(sum_with_current) / (i + 1)
- else:
- raise ValidationError(u'未处理的操作类型')
- else:
- arr1[i] += arr2[i]
- return arr1
|