我試圖在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
uj5u.com熱心網友回復:
我打算對您的默認引數寫下同樣的擔憂,但這至少在第一次被呼叫時會正常作業。這個功能沒有。每個人都跳到了那個常見的問題上,而沒有注意到下一行。讓我們再看一下這段代碼的刪減版本:
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 的值并不重要。
(對于其他閱讀此內容的人:)將我標記為“不相關”的內容分開并不完全相同,但我試圖指出輸入已被覆寫。
我認為這個函式根本不應該接受用戶輸入或有一個默認引數。讓它成為一個只有一項作業的函式,只需將資料傳遞給它即可。用戶輸入可以在別處收集。
uj5u.com熱心網友回復:
根據 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回傳一個字串值,您需要先將其轉換為整數串列,然后再開始處理它。
- 您可以換出串列推導式 for
map(int, inp1.split(" "))因為它會做同樣的事情(但map除非您list()先將它包裝在一個函式中,否則您不能多次迭代)。
其次,避免設定可變默認引數,因為(簡而言之)在多次重新運行同一個函式時會導致奇怪的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311470.html
上一篇:如何將陣列元素拆分為更多元素
下一篇:整個字串沒有大寫
