簡體   English   中英

python中最長的相等數序列

[英]Longest sequence of equal numbers in python

我試圖在python中生成最長的相等數序列,但它不起作用

def lista_egale(lst1 = input("numbers go here ")):
    l = 0
    lst1 = []
    maxi = -9999
    prev_one = None
    lmax = -9999
    for current in lst1:
        if prev_one == current:
            l += 1
        else:
            l = 1
        if l > lmax:
            lmax = l
            maxi = current
        prev_one = current
    print("longest sequence is ", lmax, " and ", maxi)

lista_egale()

輸入:

1 2 2 2 2 3 4 5 6 2 2 2

預期輸出:

longest sequence is  4  and  2

我打算對您的默認參數寫下同樣的擔憂,但這至少在第一次被調用時會正常工作。 這個功能沒有。 每個人都跳到了那個常見的問題上,而沒有注意到下一行。 讓我們再看一下這段代碼的刪減版本:

irrelevant = input("numbers go here ")

def lista_egale(lst1 = irrelevant):
    # while it is true that your default argument is bad,
    # that doesn't matter because of this next line:
    lst1 = []
    for current in lst1:
        # unreachable code
        pass

澄清一下,由於您的回復表明這還不夠清楚,如果您立即用空列表覆蓋它,傳遞給 lst1 的值並不重要。

(對於其他閱讀此內容的人:)將我標記為“不相關”的內容分開並不完全相同,但我試圖指出輸入已被覆蓋。

我認為這個函數根本不應該接受用戶輸入或有一個默認參數。 讓它成為一個只有一項工作的函數,只需將數據傳遞給它即可。 用戶輸入可以在別處收集。

根據 Barmar 的說明以及僅使用不可變默認值的原則,您的代碼應該看起來更像這樣:

def lista_egale(inp1 = None):
    if not inp1:
        inp1 = input("numbers go here ")
    # optionally do some error checking for nonnumerical characters here
    lst1 = [int(i) for i in inp1.split(" ")]

    # rest of your code here

lista_egale()

基本上, input返回一個字符串值,您需要先將其轉換為整數列表,然后再開始處理。

  • 您可以將列表map(int, inp1.split(" "))map(int, inp1.split(" "))因為它會做同樣的事情(但您不能多次遍歷map ,除非您首先將其包裝在list()函數中)。

其次,避免設置可變默認參數,因為(簡而言之)在多次重新運行同一個函數時會導致奇怪的結果。

暫無
暫無

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

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