将递归函数重写为尾递归函数

编程入门 行业动态 更新时间:2024-10-11 07:28:19
本文介绍了将递归函数重写为尾递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题:计数一次或多次掷骰子来构造总和 n 的方法的数量.每次掷出的结果在1到6之间.

Problem: Count the number of ways to construct sum n by throwing a dice one or more times. Each throw produces an outcome between 1 and 6.

解决方案:我已经为其编写了一个递归解决方案,该解决方案可以输出正确的答案.对于 n 的较大值,它应该达到堆栈溢出.因此,我想避免这种情况,并使用尾部递归方法重写代码.这是我的代码:

Solution: I have written a recursive solution for it which outputs correct answer. For large values of n it should hit stack overflow. So I want to avoid it and rewrite the code using tail recursive approach. Here's my code:

def numWays(n, arr): answer = 0 for item in arr: if item <= n: if n == item: answer += 1 else: answer += numWays(n-item, arr) return answer li = [i for i in range(1,7)] print(numWays(5, li)) #example n=5

我已经看到了将阶乘函数编写为网络上的尾递归的示例,但这很容易.无法应用该累加器技巧来将所需答案存储为函数调用中的附加参数.一般还有其他技巧吗?

I've seen example of writing factorial function as tail recursive on web but that was easy. Not able to apply that accumulator trick to store the required answer as an additional argument in the function call. Are there any other tricks which work in general?

这也可以重写为迭代函数,但是我正在寻找将递归函数转换为尾递归的方法.给定的问题,代码和Python仅作为示例.没什么特别的.

This could be rewritten as iterative function also but I am looking for ways in general to convert recursive functions to tail-recursive. The given problem, code, and Python is just for an example. Nothing specific about those.

推荐答案

一种解决堆栈溢出问题的方法是手动模拟调用堆栈.

One way for you to get around the stack overflow problem would be to simulate the callstack manually.

def numWays(n, arr): call_stack = [(n, arr)] answer = 0 while call_stack: n, arr = call_stack.pop(0) for item in arr: if item <= n: if n == item: answer += 1 else: call_stack.insert(0, (n-item, arr)) return answer li = [i for i in range(1, 7)] print(numWays(5, li))

输出:

16

更多推荐

将递归函数重写为尾递归函数

本文发布于:2023-11-29 18:43:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647277.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   函数   重写

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!