我想練習撰寫一個函式(遞回和迭代),通過乘以它的非零數字來給出給定數字的乘積。
例如:22 = 2x2 這給你 4 和 303 = 3x3 這給你 9
如果數字中的數字為零,我在這里找到的大多數解決方案都不會真正起作用。
我使用迭代嘗試了以下操作,但仍然不明白如何使用遞回方法對其進行編碼。
def digitProductI(n):
product = 1
while n > 0:
remainder = n%10
if remainder != 0:
product *= remainder
n = n//10
return product
uj5u.com熱心網友回復:
如果你想讓你的函式成為遞回函式,你需要做一些事情:
- 呼叫自身的函式
- 一個基本案例
對于您的函式,您可以使用新產品呼叫函式本身并回傳該值,而不是使用 while 回圈。然后,為了防止出現 a RecursionError,您應該添加一個基本情況,在這種情況下,如果 n <= 0 則回傳 n。撰寫此 inn 代碼將如下所示:
def digitProductI(n):
# This is the base case. If n is 0, it would return 1.
if not n:
return 1
# If n is non-zero, we find the remainder and call the function again with the floor divided value.
remainder = n % 10
if remainder:
product = remainder
else:
product = 1
return product * digitProductI(n // 10)
這將產生與原始函式相同的結果。就像在您的函式中一樣,零輸入將產生 1 作為結果,而強制零和尾隨零將被忽略。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/434911.html
標籤:python-3.x 递归 迭代
