问:运行是一系列相邻的重复值。给定一个列表,写一个函数 确定最长跑的长度。例如,对于序列[1,2,5,5,3,1,2,4,3,2,2,2,3,3,5,5,6,3,1],最长跑是4。
我遇到了麻烦,我编写了一个代码,发现最长的运行时间由数字'2'组成,但还没有得到运行的长度为4。
到目前为止,这是我的代码(我已经注释了我正在研究的部分,但是没有注意它):
# longestrun.py
# A function to determine the length of the longest run
# A run is a sequence of adjacent repeated values.
def longestrun(myList):
result = None
prev = None
size = 0
max_size = 0
for i in myList:
if i == prev:
size += 1
if size > max_size:
result = i
max_size = size
else:
size = 0
prev = i
return result
def main():
print("This program finds the length of the longest run within a given list.")
print("A run is a sequence of adjacent repeated values.")
myString = input("Please enter a list of objects (numbers, words, etc.) separated by
commas: ")
myList = myString.split(',')
longest_run = longestrun(myList)
print(">>>", longest_run, "<<<")
main()
请帮助!!! :(((
答案 0 :(得分:12)
您可以使用itertools.groupby
在一行中执行此操作:
import itertools
max(sum(1 for _ in l) for n, l in itertools.groupby(lst))
答案 1 :(得分:0)
如果您不想使用itertools和import,这应该有用。
a=[1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1]
def longestrun(myList):
result = None
prev = None
size = 0
max_size = 0
for i in myList:
if i == prev:
print (i)
size += 1
if size > max_size:
print ('******* '+ str(max_size))
max_size = size
else:
size = 0
prev = i
print (max_size+1)
return max_size+1
longestrun(a)
答案 2 :(得分:0)
另一种方法:
def longestrun(myList):
sett = set()
size = 1
for ind, elm in enumerate(myList):
if ind > 0:
if elm == myList[ind - 1]:
size += 1
else:
sett.update([size])
size = 1
sett.update([size])
return max(sett)
myList = [1, 2, 5, 5, 3, 1, 2, 4, 3, 2, 2, 2, 2, 3, 6, 5, 5, 6, 3, 1]
print longestrun(myList)
答案 3 :(得分:0)
def longestrun(myList):
size = 1
max_size = 0
for i in range(len(myList)-1):
if myList[i+1] = myList[i]:
size += 1
else:
size = 1
if max_size<size:
max_size = size
return size
从.split()
中的myList
移除main()
,您就可以使用此功能了。
答案 4 :(得分:0)
def getSublists(L,n):
outL=[]
for i in range(0,len(L)-n+1):
outL.append(L[i:i+n])
return outL
def longestRun(L):
for n in range(len(L), 0, -1):
temp=getSublists(L,n)
for subL in temp:
if subL==sorted(subL):
return len(subL)
答案 5 :(得分:0)
作为David Robinson答案的更新,现在(Python 3.4)可以在空序列上返回0(而不是引发ValueError
):
import itertools
max((sum(1 for _ in l) for n, l in itertools.groupby(lst)), default=0)