簡體   English   中英

python列表中最長的連續重復序列

[英]Longest sequence of consecutive duplicates in a python list

如前所述,運行是一系列連續重復的值。 實現一個名為longest_run 的Python 函數,它接受一個數字列表並返回最長運行的長度。 例如在序列中: 2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1最長的運行長度為4 然后,在主程序中,您的程序應該要求用戶輸入列表,然后它應該調用longest_run 函數,並打印結果。

這是我嘗試過的,但它只返回 1,我不明白為什么。 我無法為此問題導入任何模塊。

def longest_run(aList):
  '''(list)->int
  Returns length of the longest run
  Precondition: aList is a list of a len of at least 2 and elements of list are ints
  '''
  count=0
  bucket=[]
  for i in aList:
    if bucket==i:
        count=count+1
    else:
        bucket=i
        count=1
  return count

您的代碼最大的錯誤是設置bucket=[] (這是一個列表),然后設置為整數。

此外,您需要存儲最長序列和當前序列長度(初始化為 1)以及最后看到的值,因此變量比您存儲的要多。

每次值與之前相同,增加計數器。 如果不同,請在檢查它是否不大於最大值后重置計數器。 最后再次執行最大測試,以防最長的序列在最后(經典錯誤)

像這樣:

seq = [2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1]

result=1
max_result=0
last_seen=seq[0]

for v in seq[1:]:
    if v==last_seen:
        result += 1
    else:
        if result > max_result:
            max_result = result
        last_seen = v
        result = 1

# just in case the longest sequence would be at the end of your list...
if result > max_result:
    max_result = result

print(max_result)

當你最終被允許使用 python 電池時,使用itertools.groupby並計算序列長度的最大值:

max(sum(1 for x in v) for _,v in itertools.groupby(seq))

所以你想在你的列表中找到最長的相同數字? 因為它有點令人困惑,你試圖編碼什么。

您應該保留兩個版本的 count: maxCount (您要返回的actualCount )和actualCount (您要遞增的那個),遍歷列表並將 number 與下一個進行比較。 如果它是相同的actualCount += 1如果不是, actualCount = 0在每次迭代結束時actualCount = 0 ,比較maxCountactualCount並且如果actualCount大於maxCount = actualCount

def longest_run(aList):

    maxCount = 1
    actualCount = 1

    for i in range(len(aList)-1):
        if aList[i] == aList[i+1]:
            actualCount += 1
        else:
            actualCount = 1
        if actualCount > maxCount:
            maxCount = actualCount

    return(maxCount)

你得到1因為當你的循環在它的最后一次迭代中時: bucket = 20 and i = 1這意味着bucket != i所以循環進入 else 子句並分配count = 1退出並且函數返回計數為 1。

建議:

1)當您遇到這樣的錯誤時,請嘗試手動運行代碼/邏輯 - 它會有所幫助。

2)特別針對這個問題 - 每當跑步結束時,您都會忘記上次跑步的長度,請考慮如何“記住”最長的跑步。

您可以使用以下方法:(每個數字的重復次數)

mylist = [2, 7, 4, 4, 2, 5, 2, 5, 10, 12, 5, 5, 5, 5, 6, 20, 1]
my_dict = {i:mylist.count(i) for i in mylist}
mylist = list(dict.fromkeys(mylist))
R_list=[]
for i in mylist:
    print("%s repeated %s" %(i,my_dict[i]))
    R_list = R_list+[my_dict[i]]
print(R_list)
print(max(R_list))  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM