Python: 每日一题 58
- 2017-11-27 13:46:00
- 六月
- 来源:
- http://bbs.fishc.com/thread-88065-1-1.html
- 转贴 475
当有多个组合时,返回倒序数字最大的那一组数组。
是不是看文字有点难懂呢?看例子:
- decompose(11) --->[1,2,4,10] 11**2 = sum(map(lambda x:x**2,[1,2,4,10]))
- [2,6,9] 虽然也满足条件,但是因为9小于10,所以不是结果
再看一个列子:
- decompose(50) ---> [1, 3, 5, 8, 49]
当然[11],[50]也是不能做为答案的(这就不要算了),[1,1,1,…,1]也是不可以的。如果没有合适的结果,那么就返回None。
- def decompose(n):
- total = 0
- answer = [n]
- while len(answer):
- temp = answer.pop()
- total += temp ** 2
- for i in range(temp - 1, 0, -1):
- if total - (i ** 2) >= 0:
- total -= i ** 2
- answer.append(i)
- if total == 0:
- return sorted(answer)
- return None
发表评论