為什么以下執行使得該print陳述句被呼叫的頻率與它的遞回一樣多,但計數變數count, whenx == 1從未達到。
def count_bits(n, count = 0):
x = n % 2
if n == 1:
return count 1
if n < 1:
return count
if x == 1:
count = 1 # when x == 1
count_bits(int(n/2), count)
print("counter")
return count
為什么有必要用
return陳述句遞回?因為如果遞回呼叫在return陳述句之上,代碼會回傳錯誤的輸出,但是使用關鍵字呼叫遞回呼叫return,一切正常。通常,該
另一方面,如果在遞回呼叫之后跟隨“return”,它會正確地從基本條件回傳計數。
def count_bits(n, count = 0):
x = n % 2
if n == 1:
return count 1
if n < 1:
return count
if x == 1:
count = 1
return count_bits(int(n/2), count)
uj5u.com熱心網友回復:
您必須回傳遞回結果,因為遞回函式的含義是to count current step you have to get result of previous step
F_k = F_k-1 * a b # simple example
意味著您必須F_k-1從 F_k 獲取結果并使用它計算當前結果。
uj5u.com熱心網友回復:
我建議你使用snoop包來更有效地除錯你的代碼,通過這個包你可以逐步跟蹤執行。安裝它運行:
Pip install snoop
Import snoop
將 snoop 裝飾器添加到 count_bits()
有關該軟體包的資訊,請參見此鏈接 https://pypi.org/project/snoop/
uj5u.com熱心網友回復:
這兩種方法的輸出差異是因為 python 處理基本資料型別的方式。基本資料型別如浮點、整數、字串等通過值傳遞,而復雜資料型別如字典、串列、元組等通過參考傳遞。因此,對函式內的基本資料型別所做的更改只會在函式的本地范圍內進行更改,但是對復雜資料型別的更改將更改原始物件。請參閱下面的示例:
x = 5
def test_sum(i : int):
print(i)
i = 5
print(i)
# the integer value in the global scope is not changed, changes in test_sum() are only applied within the function scope
test_sum(x)
print(x)
y = [1,2,3,4]
def test_append(l : list):
print(l)
l.append(10)
print(l)
# the list in the global scope has '10' appended after being passed to test_append by reference
test_append(y)
print(y)
發生這種情況是因為在計算上傳遞對記憶體中大物件的參考比將其復制到函式的本地范圍內要便宜得多。有關差異的更多資訊,可以通過搜索“編程中的參考和價值之間的區別是什么”獲得數千種資源。
至于你的代碼,在我看來唯一的區別是你應該改變你的第一個片段如下:
def count_bits(n, count = 0):
x = n % 2
if n == 1:
return count 1
if n < 1:
return count
if x == 1:
count = 1 # when x == 1
# assign the returned count to the count variable in this function scope
count = count_bits(int(n/2), count)
print("counter")
return count
您撰寫的第二個代碼片段幾乎相同,只是沒有將新值分配給“count”變數。這回答了你的問題了嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424931.html
