我想重写这个函数,所以它使用递归。我目前失去了做什么。任何人都可以给我一些方向吗?
解决方案这是一个可能的解决方案:
def数字(n):如果n < 10: return [n] 返回数字(n / 10)+ [n%10] 数字(123)> [1,2,3]上述解决方案修复了代码中的错误,数字以相反的顺序。另请注意, n 必须是一个大于或等于零的整数才能产生正确的结果。
作品:
调用在一个较小的数字上 - 即没有我们刚刚处理的最后一位数字的数字。
现在我们继续调用堆栈:
[1] [1] + [2] [1,2] + [3] [1,2,3]编辑:
接受@ thg435的挑战,这是一个尾递归解决方案: def digits(n): def loop(i,acc): if i< 10: return [i] + acc return loop(i / 10,[i%10] + acc) return loop(n,[])def digits(n): res = [] while n > 0: res.append(n % 10) n /= 10 return res
I want to rewrite this function so it uses recursion. I'm currently lost as to what to do. Can anyone give me some direction?
解决方案Here's a possible solution:
def digits(n): if n < 10: return [n] return digits(n/10) + [n%10] digits(123) > [1, 2, 3]The above solution fixes a bug in your code, you were returning the digits in reverse order. Also notice that n must be an integer greater than or equal to zero for producing correct results.
Here's how it works:
The call to digits(123) will look like this at each step of the recursion:
digits(123) = digits(123/10) + [3] digits(12) = digits(12/10) + [2] digits(1) = [1]Now we go up the call stack:
[1] [1] + [2] [1, 2] + [3] [1, 2, 3]EDIT :
Accepting @thg435's challenge, here's a tail-recursive solution:
def digits(n): def loop(i, acc): if i < 10: return [i] + acc return loop(i/10, [i%10] + acc) return loop(n, [])
更多推荐
如何将此函数重写为递归函数?
发布评论