我需要编写一个函数,给出一个整数列表,如果列表包含一个连续的值序列,其总和为,L
则返回,否则返回。True
n
False
假设我的列表是:L = [2,2,4,4,0,0,2,8]
and n
= 3。该函数应该返回,False
因为没有连续的值总和为 3。
要求:不允许使用 Python 的模块
我试过:
def consecutive(L,n):
for i in range(len(L)):
for j in range(i+1, len(L)):
if sum(L[i:j+1])==n:
return True
return False
L = [2,2,4,4,0,0,2,8]
consecutive(L,3)
这是部分工作,因为当我设置时n=12
,它返回True
。我知道切片需要解决一些问题,但我不知道它是什么。
主要问题很简单:在这种情况下,范围必须是 len+1,否则在边缘情况下会失败。工作代码是:
def consecutive(L, n):
for i in range(len(L)+1):
for j in range(i+1,len(L)+1):
s=sum(L[i:j])
if s == n:
print(i,j,s,'TRUE') #DEBUG: remove when done
#return True #uncomment this to reintegrate
else: print(i,j,s) #DEBUG: remove when done
return False
L = [2,2,4,4,0,0,2,-3]
consecutive(L,3)
更好的是,在您的示例中,您没有显示负数。如果您没有否定,您可以通过在超过搜索值 n 时跳过循环来提高代码效率:
def consecutive(L, n):
for i in range(len(L)+1):
for j in range(i+1,len(L)+1):
s=sum(L[i:j])
if s == n:
print(i,j,s,'TRUE') #DEBUG: remove when done
#return True #uncomment
elif s > n:
print(i,j,s,'too big') #DEBUG: remove when done
break
else: print(i,j,s) #DEBUG: remove when done
return False
L = [2,2,4,4,0,0,2,1]
consecutive(L,3)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句