python-3.x - 将Python迭代函数转换为递归函数

标签 python-3.x

请考虑 2 个交叉套件:

U0 = 1
V0 = 2
Un = 2U(n-1) + 3 V(n-1)
Vn = U(n-1) + V(n-1)

我想用这个Python迭代函数来解决它:

def myfunction(n=5):
  u = 1
  v = 2
  for i in range(n):
    w = u
    u = 2*u + 3*v
    v = w + v
  
  return(u,v)

我更喜欢递归函数,但我不知道如何转换我的函数。 你有什么主意吗? 谢谢。

最佳答案

很简单:

def u(n):
    if n == 0:
        return 1
    else:
        return 2*u(n-1) + 3*v(n-1)
    
def v(n):
    if n == 0:
        return 2
    else:
        return u(n-1) + v(n-1)

print((u(5), v(5))) # -> (905, 393)

这是可能的,因为 Python 是一种动态解释编程语言。

编辑:

def myfunction(n):
    def u(n):
        if n == 0:
            return 1
        else:
            return 2*u(n-1) + 3*v(n-1)
        
    def v(n):
        if n == 0:
            return 2
        else:
            return u(n-1) + v(n-1)
    return u(n), v(n)

print(myfunction(5)) # -> (905, 393)

只是为了符合您的确切问题/功能。

关于python-3.x - 将Python迭代函数转换为递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69966526/

相关文章:

python - Pyinstaller + Django = 没有名为 'django.core.context_processors' 的模块

Python 源代码 - 更新语法

python - 列表内的映射转换

python-3.x - 回溯错误 : Lookup Error: unknown encoding charmap

python - 如果与 Python 中的 Elif 相比,哪个更好?

python - 在 Python Pandas 的列中为每个 na 填充唯一值

python-3.x - Scrapy - 从多个页面中提取数据

python - 使 glob 目录变量

python - 使用 float 创建 if 语句

python-3.x - 如何访问Gathering Future完成结果里面的数据