【问题标题】:All possible set of digits that sum==n in python list [closed]python列表中所有可能的总和==n的数字集[关闭]
【发布时间】:2013-03-23 04:16:09
【问题描述】:

我想根据 n 对列表进行一些更改。例如:

l=[0,0,0,0,0,0,0,0,0,0,0,0] n=4:

 print   l   #first iteration will print :[1,1,1,1,0,0,0,0,0,0,0,0]    # 4=1+1+1+1
 print   l   #next iteration will print :[1,1,0,2,0,0,0,0,0,0,0,0]    # 4=1+1+2
 print   l   #next iteration will print :[0,2,0,2,0,0,0,0,0,0,0,0]    # 4=2+2
 print   l   #next iteration will print :[1,0,0,3,0,0,0,0,0,0,0,0]    # 4=1+3
 print   l   #last iteration will print :[0,0,0,4,0,0,0,0,0,0,0,0]    # 4=4

列表中的序列对我来说无关紧要,但元素必须远离 =>9 应该是 sum==n.Rest 用零填充的所有可能的数字集

【问题讨论】:

  • 问题很不清楚,为什么每个示例都有多个列表?这些数字背后的逻辑是什么?
  • 如果 n > len(l) 会怎样?错误?
  • 我也不明白编号背后的逻辑。此外,您可能想要一个列表列表,而不是重复重新分配 l
  • n 不会大于 len(l)
  • 如果列表一开始就用零填充,你用什么方式填充它?

标签: python list


【解决方案1】:
l=[0,0,0,0,0,0,0,0,0,0,0,0]
n = 11

for i in range (0,n):
        l[i] = 1 

print l
carryidx = 0 
for i in reversed(range(0,n - 1)):
        v = l[ n - 1] + l[i]
        if v > 9:
                while l[carryidx] > 9:
                        carryidx += 1
                l[carryidx] += 1
        else:
                l[n - 1] = v 
        l[i] = l[i] - 1 
        print l

输出

[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 0, 2, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0]

【讨论】:

  • 几乎可以,对不起,我会编辑问题
  • 为什么没有 [0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0]?
  • @gnibbler,这回答了一个较旧的、不清楚的问题版本
猜你喜欢
  • 2013-10-06
  • 2011-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
相关资源
最近更新 更多