擅长:python、mysql、java
<p>它实际上并不复杂,您可以使用<code>itertools.combinations</code>生成数字组合,然后使用<code>zip</code>应用一个因子,并获取每个项目和<code>sum</code>的乘积</p>
<p>例如,系数为[1,101001000]的[1,2,4,5]将给出1+20+400+5000=5421</p>
<p>诀窍在于<code>combinations</code>总是以定义的顺序(从早到晚)生成组合,因此<code>combinations([1,2,3], 2)</code>将给出<code>[(1, 2), (1, 3), (2, 3)]</code></p>
<pre><code>from math import prod
n = 5
factors = [10**i for i in range(n)]
[sum(map(prod, zip(factors, c)))
for i in range(n,0,-1)
for c in combinations(range(1,n+1), i)]
</code></pre>
<p>输出:</p>
<pre><code>[54321,
4321,
5321,
5421,
5431,
5432,
321,
421,
521,
431,
531,
541,
432,
532,
542,
543,
21,
31,
41,
51,
32,
42,
52,
43,
53,
54,
1,
2,
3,
4,
5]
</code></pre>
<p>如果需要严格的输出顺序,请使用以下方法(效率稍低):</p>
<pre><code>[sum(map(prod, zip(factors, c)))
for i in range(n,0,-1)
for c in list(combinations(range(1,n+1), i))[::-1]]
</code></pre>
<p>输出:</p>
<pre><code>[54321,
5432,
5431,
5421,
5321,
4321,
543,
542,
532,
432,
541,
531,
431,
521,
421,
321,
54,
53,
43,
52,
42,
32,
51,
41,
31,
21,
5,
4,
3,
2,
1]
</code></pre>