Python: 每日一题 58

2017-11-27 13:46:00
六月
来源:
http://bbs.fishc.com/thread-88065-1-1.html
转贴 475
根据给定的数字(n)返回一个升序的数组,数组中的值的平方和等于给定数(n)的平方。
当有多个组合时,返回倒序数字最大的那一组数组。

是不是看文字有点难懂呢?看例子:
  1. decompose(11)    --->[1,2,4,10]       11**2 = sum(map(lambda x:x**2,[1,2,4,10]))   
  2.                                      [2,6,9]           虽然也满足条件,但是因为9小于10,所以不是结果

再看一个列子:
  1. decompose(50)  ---> [1, 3, 5, 8, 49]

当然[11],[50]也是不能做为答案的(这就不要算了),[1,1,1,…,1]也是不可以的。如果没有合适的结果,那么就返回None。


  1. def decompose(n):
  2.     total = 0
  3.     answer = [n]
  4.     while len(answer):
  5.         temp = answer.pop()
  6.         total += temp ** 2
  7.         for i in range(temp - 1, 0, -1):
  8.             if total - (i ** 2) >= 0:
  9.                 total -= i ** 2
  10.                 answer.append(i)
  11.                 if total == 0:
  12.                     return sorted(answer)
  13.     return None
复制代码
发表评论
评论通过审核后显示。