我想练习写一个函数(递归和迭代),通过乘以它的非零位数,给出一个给定数字的乘积。
例如: 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
发布于 2022-02-28 09:09:47
如果您想使您的函数成为递归函数,则需要以下几点:
对于您的函数,您可以使用新产品调用函数本身,而不是使用while循环,并返回该值。然后,为了防止RecursionError
,您应该添加一个基本情况,在本例中,这是如果n <= 0返回n。编写这个客栈代码应该如下所示:
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://stackoverflow.com/questions/71292487
复制相似问题