一般的编程题,注意计算份额的时候使用 int( 100 * x / sum )

1 class Bonuses: 2 def getDivision(self, points): 3 pointSum = 0 4 for x in points: 5 pointSum += x 6 7 bounus = [] 8 bounusSum = 0 9 for x in points: 10 bou = int(100 * x / pointSum) 11 bounus.append(bou) 12 bounusSum += bou 13 14 p = sortPoints(points) 15 for i in range(0, 100 - bounusSum): 16 x = p[i] 17 bounus[x[0]] = bounus[x[0]] + 1 18 return tuple(bounus) 19 20 21 def sortPoints(points): 22 p = [] 23 for i in range(0, len(points)): 24 p.append((i, points[i])) 25 p.sort(key = lambda x: (-x[1], x[0])) 26 return p 27 28 29 # test 30 o = Bonuses() 31 assert(tuple(sortPoints([1,2,3])) == ((2,3), (1,2), (0,1))) 32 33 # test: len(points) == 1 34 assert(o.getDivision((5,)) == (100,)) 35 36 # test case 37 assert(o.getDivision((1,2,3,4,5)) == ( 6, 13, 20, 27, 34 ) ) 38 assert(o.getDivision((5,5,5,5,5,5)) == ( 17, 17, 17, 17, 16, 16 ) ) 39 assert(o.getDivision((485, 324, 263, 143, 470, 292, 304, 188, 100, 254, 296, 40 255, 360, 231, 311, 275, 93, 463, 115, 366, 197, 470)) == ( 8, 6, 4, 2, 8, 5, 5, 3, 1, 4, 5, 4, 6, 3, 5, 4, 1, 8, 41 1, 6, 3, 8 ) )