python - 在 Python 中使用递归

标签 python recursion

我正在尝试使用递归解决一个问题,如果我使用“if”语句,该问题将非常冗长。我想看看 const = 50 在 n 中出现了多少次。我想返回 50 在 n 中出现的次数。我知道这很简单,但我想使用递归来完成此任务,这对我来说并不简单。条件如下:

0 < n == 50 -> 1 instance
50 < n <= 100 -> 2 instance
100 < n <= 150 -> 3 instance
150 < n <= 200 -> 4 instance
200 < n <= 250 -> 5 instance
...
...
...

以下是我开始的内容,但我陷入了困境:

def num_of_times(n)
""" (int) => int 
when n is entered count 1 for every 50 found. If any number is over 50, yet does not
equal another 50 (e.g. n = 60; 60 - 50 = 10; 50 -> 1; 10 -> 1) will call for a count, which would be a count of 2 in this case.

>>>num_of_times(60)
2
>>>num_of_times(200)
4
"""
    count = 0

    if n > 0 and n == 50:
        count += 1
    elif n > 50:
       """ Here is where my thinking is going to sleep"""
       ...
       ...
       ...

预先感谢您提供的任何帮助。

最佳答案

对于这个特定问题,您应该只使用除法:

count = n // 50 + 1  

(注意使用双斜杠,而不仅仅是“/” - 即 确保即使在 Python 3 上也会执行整数除法, 结果四舍五入,而不是给你一个 float 值作为结果)

现在,关于递归 - 这不是在 Python 中解决问题的首选方法 - 可能具有相同成本的递归函数 “针对函数调用进行优化”中的迭代“for 循环” 语言,如方案,最好使用 forwhile 循环来处理。

继续这个例子 - 并导致递归 - 您需要更改两者 您的数据输入以及每次交互的结果 - 这样当 您的数据不需要记录器处理,您得到了最终结果:

count = 0
while n >= 50:
   count += 1
   n -= 50

从这里,可以更容易地检查递归方法应该做什么: 每个连续的调用都应该收到“n”和“count”的修改值 比上一次迭代。您可以利用Python的 可选参数语法,以便第一次调用该函数时不会 必须添加“count”参数:

def num_of_times(n, count=0):
    if n < 50:
        return count
    return num_of_times(n - 50, count + 1)

由于解释器上设置的调用堆栈深度,Python 中的 n = 大约 50000,默认最大递归深度设置为 1000。您可以通过在 sys 中设置来更改该数字 模块 - 但这绝对不是 Python 中推荐的方法 - 既考虑到函数调用的开销,也考虑到 whiefor 的更高级别的设施结构体。对于某些会递归 2 - 100 次的函数(例如处理文件路径、URL 部分等的函数)来说,这显然是可以的 - 特别是当该函数最终比交互式对应函数更具可读性时。

关于python - 在 Python 中使用递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885239/

相关文章:

python - Pandas 将不同大小的数据帧连接到列末尾

recursion - Prolog 递归和终止

javascript - 为什么 setTimeout 在循环内与递归函数内无法正确执行

c - 在 C 中创建递归数据结构的方法

php - 在 PHP 中处理 Python 异常/错误

Python:使用 csv 模块有效读取文件

scala - Scala 中的组合数学 : How to iterate/enumerate all possibilities to merge multiple sequences/lists (riffle shuffle permutations)

node.js - 将树递归展开为迭代程序

python - 尝试使用 CV2 从网络摄像头捕获视频时出错

python - 如何在 Behave 环境设置期间运行 Tornado IO Loop