我正在尝试编写一个函数。该函数将一个数字列表作为输入,在该列表中找到最大的连续数字序列,并返回一个仅包含原始列表的最大数字序列的列表。
例子:
In [2]: largestSeq([1,2,3,4,1,2,3])
Out[2]: [1, 2, 3, 4]
只要输入列表中有 0 个或超过 1 个元素,它就可以工作。我在我的代码中包含了打印语句以查看错误在哪里。
这是调用largestSeq([1])
and的代码和结果largestSeq([1,2])
:
代码:
def findSeq(seq): #this finds a sequence of consecutive numbers
i = 0 #in a list and returns it
if len(seq) <= 1: #it stops when the next number in the list
return seq #is smaller than the former
s =[seq[0]]
while seq[i] < seq[i+1]:
i += 1
s.append(seq[i])
if i == len(seq)-1:
break
return s
def largestSeq(seq,a=[]):
b = findSeq(seq) #find the first consecutive sequence
if len(seq) == 0:
return a
print 'Length of b is ' + str(len(b))
if len(b) > len(a): #check if found sequence is bigger than
print 'seq is now ' + str(seq)#the last found sequence
print 'b is now ' + str(b)
i = len(b)
print 'now deleting elements of seq'
for d in range (i):
seq.remove(seq[0]) #remove found sequence from the original
#del seq[0:i] #list
print 'seq is now ' + str(seq)
print 'b is now ' + str(b)
return largestSeq(seq,b) #start over
else:
del seq[0:len(b)]
return largestSeq(seq,a)
现在电话:
In [14]: largestSeq([1])
Length of b is 1
seq is now [1]
b is now [1]
now deleting elements of seq
seq is now []
b is now []
Out[14]: []
largestSeq([1,2])
Length of b is 2
seq is now [1, 2]
b is now [1, 2]
now deleting elements of seq
seq is now []
b is now [1, 2]
Out[15]: [1, 2]
请注意,在第一次调用中,b
删除元素后,元素 in 也被删除seq
,尽管我没有更改它!在第二次通话[1,2]
b
中表现得像我想要的那样,而seq
被删除。
我尝试使用list.remove
和使用del
(已注释掉并产生相同的错误)来操作列表。
里面发生了什么?我不明白。我希望b
在第一次通话中保持不变,就像在第二次通话中一样。
这是一个非常具体的问题。我将不胜感激任何建议!