Q)执行代码后需要打印值[1,12,123,2,23,3,13],但是得到[1,12,123,2,23,3]。我错过了这封信13.任何人都可以告诉我克服这个错误的原因吗?
def get_all_substrings(string):
length = len(string)
list = []
for i in range(length):
for j in range(i,length):
list.append(string[i:j+1])
return list
values = get_all_substrings('123')
results = list(map(int, values))
print(results)
count = 0
for i in results:
if i > 1 :
if (i % 2) != 0:
count += 1
print(count)
答案 0 :(得分:1)
for
中嵌套get_all_substrings()
循环中非常简单的问题,让我们走吧!
您正在迭代字符串123
的每个元素:
for i in range(length) # we know length to be 3, so range is 0, 1, 2
然后,您从当前i
迭代每个后续元素:
for j in range(i,length)
最后,使用切片运算符将位置从i
添加到j+1
:
list.append(string[i:j+1])
但究竟发生了什么?那么我们可以继续前进!
i
的第一个值是0
,所以我们跳过第一个for
,转到第二个:
for j in range(0, 3): # i.e. the whole string!
# you would eventually execute all of the following
list.append(string[0:0 + 1]) # '1'
list.append(string[0:1 + 1]) # '12'
list.append(string[0:2 + 1]) # '123'
# but wait...were is '13'???? (this is your hint!)
i
的下一个值是1:
for j in range(1, 3):
# you would eventually execute all of the following
list.append(string[1:1 + 1]) # '2'
list.append(string[1:2 + 1]) # '23'
# notice how we are only grabbing values of position i or more?
最后,您到i
2
:
for j in range(2, 3): # i.e. the whole string!
# you would eventually execute all of the following
list.append(string[2:2 + 1]) # '3'
我已经向您展示了正在发生的事情(正如您在问题中提到的那样),我留给您设计自己的解决方案。几个笔记:
i
list
对象list
)答案 1 :(得分:0)
我会尝试使用itertools和powerset()食谱
这样的东西from itertools import chain, combinations
def powerset(iterable):
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
output = list(map(''.join, powerset('123')))
output.pop(0)
答案 2 :(得分:0)
这是另一种选择,使用组合
from itertools import combinations
def get_sub_ints(raw):
return [''.join(sub) for i in range(1, len(raw) + 1) for sub in combinations(raw, i)]
if __name__ == '__main__':
print(get_sub_ints('123'))
>>> ['1', '2', '3', '12', '13', '23', '123']