我有兩個問題正在出現我想了解的錯誤。它們可能出于類似的原因,因此我在這篇文章中將它們組合在一起。我在這里學習如何理解解決此類錯誤!
首先,一個函式旨在在包含整數、浮點數和字串的串列中查找偶數。出于某種原因,我收到一條錯誤訊息,指出并非我的所有引數都能夠在字串格式化期間進行轉換。這是我的代碼:
def recEvenNumbers(lst):
'return a count of all the even numbers(ints and floats) in the list'
evens = 0
if lst == []:
return
else:
if type(lst[0])== int or float:
if ((lst[0]%2*10))==0:
evens = evens 1
return recEvenNumbers(lst[1:], evens 1)
我相信除了這個錯誤之外,我已經完成了整個功能。為什么會發生這種情況,我將來如何防止這種情況發生?
我遇到的另一個錯誤是針對不同的功能。這是那個的代碼:
def recMerge(a,b):
'Merge two strings together recursivly'
if len(a)==0:
return
elif len(b)==0:
return
else:
if type(a) == str:
if type(b) == str:
return a[0] b[0] recMerge(a[1:], b[1:])
此函式的目的是合并兩個字串以創建一個字串,該字串的字符在兩個字串中的每一個之間交替。不過對我的問題并不重要,我只是想知道為什么我可能會在這里遇到 TypeError。這是它告訴我的:
File "C:/Users/1734/py.py", line 59, in recMerge
return a[0] b[0] recMerge(a[1:], b[1:])
TypeError: can only concatenate str (not "NoneType") to str
>>>
為什么會這樣?我假設我的 if type(a) 和 if type(b) 應該處理這個問題。為什么我不能在這種情況下使用它們?還是我只是濫用它們?
另外,這兩個錯誤是否相關?我知道這個問題可能看起來很奇怪,但如果這些問題中的某些元素我很難理解,我想指出它是什么以及為什么我誤解了它。
謝謝你的時間!
uj5u.com熱心網友回復:
你犯了一個經典的錯誤。此陳述句不會執行您認為的操作:
if type(lst[0])== int or float:
這被 P??ython 決議為:
if (type(lst[0])== int) or (float):
由于“浮動”始終為真,因此您將始終選擇if此處。當 lst[0] 是一個字串時,'%' 運算子就是字串格式化運算子。你要:
if type(lst[0]) in (int, float):
甚至
if isinstance(lst[0],int) or isinstance(lst[0],float):
uj5u.com熱心網友回復:
正如蒂姆·羅伯茨所描述的,第一個函式有一個錯誤。此外,您在遞回呼叫中向它傳遞了太多引數(evens無論如何都會被重置)。我建議深入研究 Python 基礎知識來清理它。
第二個函式有一個簡單的錯誤。當你return什么都不說的時候,你會回來的None。因此NoneType錯誤。為了解決這個問題,我相信回傳空字串 ( "")就足夠了。
uj5u.com熱心網友回復:
您的第二個函式的問題在于None,對于輸入為空的基本情況,它回傳而不是空字串。由于您的遞回通過添加到遞回呼叫的結果上來作業,因此最后一個遞回呼叫必須是您可以添加的內容。
def recMerge(a: str, b: str) -> str:
"""Merge two strings together recursively. If the strings are of
unequal length, the remainder of the longer string is dropped."""
# Type check (not necessary if you type-annotate and mypy your code!)
if not isinstance(a, str) or not isinstance(b, str):
raise TypeError("both parameters must be strings!")
# Base case: if one param is empty, there's nothing to merge, so return ""
if not a or not b:
return ""
# Recurse with a smaller slice of both parameters.
return a[0] b[0] recMerge(a[1:], b[1:])
uj5u.com熱心網友回復:
對于第一個遞回函式,這是正確的代碼
def recEvenNumbers(lst, evens):
if not lst:
return evens
if type(lst[0]) == int:
if(lst[0]%2 == 0):
return recEvenNumbers(lst[1:], evens 1)
else:
return recEvenNumbers(lst[1:], evens)
else:
return recEvenNumbers(lst[1:], evens)
x = recEvenNumbers([1, 2, 3, 4, 5.3, 7, 8, "h", 46, "32"], 0)
print(x)
在撰寫遞回函式時回傳很重要,否則會得到“None”。當您呼叫函式時,請確保添加每個引數 ex:(last,evens)。
uj5u.com熱心網友回復:
我知道其他人都在評論你的第一個問題,但如果你做對了,它就會起作用。也就是說,您應該首先處理字串并添加evens為 None 引數以檢查第一次傳遞的實體。
這是一個作業功能:
def recEvenNumbers(lst, evens = None):
'return a count of all the even numbers(ints and floats) in the list'
if evens is None:
evens = [0]
if lst:
# To keep things organized, extract first item
# into variable and the rest into a smaller list with
# star selection
item, *lst = lst
# Check for string first
# Pass rest of process if detected.
if type(item) == str:
pass
# Continue as you were before
elif type(item) == int or float:
if item % 2 * 10 == 0:
evens[0] = 1
# Recurse with appropriate params.
return recEvenNumbers(lst, evens)
# Return result.
return evens[0]
運行函式:
test_list = [1, 2.2, 4, "string"]
recEvenNumbers(test_list)
輸出:
1
第2部分:
# Function with commentary.
def recMerge(a, b):
'Merge two strings together recursivly'
# Check types
if type(a) == type(b) == str:
# Run until b is empty.
if len(b) > 0:
# Deconstructing into single and rest of items with asterisk.
aa, *a_rest = a
bb, *b_rest = b
# New `a` value that prepends the rest of a in
# front of the concatenation of the current a and b characters.
# Since a_rest is a list, we should "collect" the items back into
# a proper string format.
a = "".join(a_rest) aa bb
# Return the new a with another concatenated list for the
# remaining b items.
return recMerge(a, "".join(b_rest))
# Return a. Ensure that it is a string.
return "".join(a)
運行測驗用例:
A = "abc"
B = "def"
recMerge(A, B)
輸出:
'adbecf'
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340410.html
