在 for 循环之后,i
将是 3。因此del digitlist [i]
将删除第 3 个元素而不是第 1 个元素。将其替换为del digitlist [0]
. 此外,len(digitlis)<sequence_len
在您的 while 语句中,条件应该是len(digitlis)>=sequence_len
. 最后是拼写错误;len(digitlis)
应该是len(digitlist)
。
更正的代码:
number = 96154# Replace ??? with a value of your choice.
sequence_len = 3 # Replace ??? with a value of your choice.
sum=0
numbstr=str(number)
digitlist=[]
for digit in numbstr:
digitlist.append(int(digit))
# len(digitlis)<sequence_len → len(digitlist)>sequence_list
while sum!=10 or len(digitlist)>sequence_len: #
sum=0
if len(digitlist)>=3:
for i in range(0,3):
sum=sum+digitlist[i]
del digitlist [0] # del digitlist [i] → del digitlist [0]
print sum
利用 Python 功能的更紧凑的版本:
DESIRED_SUM=10
number = 96154# Replace ??? with a value of your choice.
sequence_len = 3 # Replace ??? with a value of your choice.
digit_list = list(map(int,str(number)))
# Note that if len(digit_list)-sequence_len+1 is negative, the range function will return an empty list, making the generator comprehension empty. any() returns False on an empty iterator (a generator is an iterator).
indexes = [i for i in range(len(digit_list)-sequence_len+1) if sum(digit_list[i:i+sequence_len])==DESIRED_SUM]
if len(indexes) > 0:
print "{sequence_len} consecutive digits in {number} have a sum of {DESIRED_SUM}.".format(**vars())
else:
print "No {sequence_len} consecutive digits have a sum of {DESIRED_SUM}.".format(**vars())