<p>以下代码导致N=14的可能性为6,而不是4</p>
<p><strong>代码</strong></p>
<pre><code>from itertools import chain, combinations
from pprint import pprint
# flatten and powerset from
# https://docs.python.org/3/library/itertools.html#itertools-recipes
def flatten(list_of_lists):
"Flatten one level of nesting"
return chain.from_iterable(list_of_lists)
def powerset(iterable):
"powerset([1,2,3]) > () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
def solve(n):
" Get all possible permutations of list of perfect squares formed by breaking a number "
squares = (i*i for i in range(1, int(b**0.5)+1)) # squares that can be used
multiples = ([i]*int(b//i) for i in squares) # repetition of squares that can be used
numbers = flatten(multiples) # flatten to single list
# Compute set of powerset, and take results which sum to b
return [x for x in set(powerset(numbers)) if sum(x) == b]
</code></pre>
<p><strong>测试</strong></p>
<pre><code>b = int(input('input number: ')) # Enter 14
result = solve(b)
pprint(result)
</code></pre>
<p><em>输出</em></p>
<pre><code>input number: 14
[(1, 1, 1, 1, 1, 1, 4, 4),
(1, 1, 1, 1, 1, 9),
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4),
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
(1, 4, 9),
(1, 1, 4, 4, 4)]
</code></pre>
<p><strong>限制最大长度</strong></p>
<pre><code>def solve_maxlen(n, maxlen):
" Get all possible permutations of list of perfect squares formed by breaking a number "
squares = (i*i for i in range(1, int(b**0.5)+1)) # squares that can be used
multiples = ([i]*int(b//i) for i in squares) # repetition of squares that can be used
numbers = flatten(multiples) # flatten to single list
# Compute set of powerset, and take results which sum to b
return [x for x in set(powerset(numbers)) if sum(x) == b and len(x) <= maxlen]
pprint(solve_maxlen(14, 6))
</code></pre>
<p><em>输出</em></p>
<pre><code>[(1, 1, 1, 1, 1, 9), (1, 4, 9), (1, 1, 4, 4, 4)]
</code></pre>