-2
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))

while sum!=10 or len(digitlis)<sequence_len:
sum=0
if len(digitlist)>=3:
    for i in range(0,3):
        sum=sum+digitlist[i]
    del digitlist [i]

print sum

代码需要检查是否存在其和为 10 的后续数字序列(例如 3 )的和并打印有关它的信息

我的代码有什么问题?

4

3 回答 3

0

在 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())
于 2013-10-31T14:16:39.127 回答
0

首先:

digitlist=[]

for digit in numbstr:
 digitlist.append(int(digit))

可以简单地替换为:

digitlist = [int(i) for i in str(number)]

要计算总和,只需调用列表中的 sum 函数:

sum(digitlist)
于 2013-10-31T14:23:09.100 回答
0

几个问题:

  1. ...len(digitlis)<sequence_len...,您的变量缺少t.
  2. 其次,我不知道你的代码是做什么的,逻辑不是直观。

然而,这是一个简单的程序,它可以做你想做的事情,我尽可能地简单:

number = 343703  # Replace ??? with a value of your choice.
sequence_len = 3  # Replace ??? with a value of your choice.
numbstr = str(number)
digitlist = []

# Appending all the numbers to a list
for digit in numbstr:
    digitlist.append(int(digit))

# Looping over all the variables in digitlist, i is the index
for i, _ in enumerate(digitlist):
    # If the index, i is 2 less than the length of the list
    if i < len(digitlist) - 2:
        # Adding the term and the next two terms after that
        if digitlist[i] + digitlist[i+1] + digitlist[i+2] == 10:
            # Printing the list
            print digitlist[i:i+3]

工作示例。

于 2013-10-31T14:24:18.873 回答