阿克曼函数与 n 个嵌套循环
我正在阅读一本关于计算的书(Minksy 1967),并且很难将递归函数与根据循环定义的函数联系起来。具体来说,他要求找到两个函数之间的关系:
Ackermann 函数(Python 中的所有代码):
def a(n,m):
if n==0:
return m+1
if m==0:
return a(n-1,1)
return a(n-1,a(n,m-1))
以及一个使用 n 个嵌套循环进行计算的函数:
def p(n,m):
for i_1 in range(m):
for i_2 in range(m):
...
for i_n in range(m):
m+=1
编写此函数(使用一个循环)的递归方法是:
def p(n,m):
if n==0:
return m+1
for i in range(m):
m=p(n-1,m)
return m
或者一种完全递归的方法写成:
def p(n,m):
return P(n,m,m)
def P(n,k,m):
if n==0:
return m+1
if k==1:
return P(n-1,m,m)
m=P(n,k-1,m)
return P(n-1,m,m)
这两个函数有什么简单的联系方式吗?我感觉自己在迷雾中爬行 - 如果您能给我提供有关如何解决此类问题的任何见解,我将不胜感激。另外,有没有办法在不引入第三个参数的情况下实现完全递归循环函数?谢谢。
I'm working my way thorugh a book on computation (Minksy 1967) and am having a hard time with relating a recursive function to a function defined in terms of loops. Specifically he asks to find the relationship between two functions:
The Ackermann function (all code in python):
def a(n,m):
if n==0:
return m+1
if m==0:
return a(n-1,1)
return a(n-1,a(n,m-1))
And a function that computes with n nested loops:
def p(n,m):
for i_1 in range(m):
for i_2 in range(m):
...
for i_n in range(m):
m+=1
A recursive way of writing this (with one loop) is:
def p(n,m):
if n==0:
return m+1
for i in range(m):
m=p(n-1,m)
return m
Or a fully recursive way to write it would be:
def p(n,m):
return P(n,m,m)
def P(n,k,m):
if n==0:
return m+1
if k==1:
return P(n-1,m,m)
m=P(n,k-1,m)
return P(n-1,m,m)
Is there some simple way these two functions are related? I feel like I'm crawling around in a fog - any insight you could give me into how to approach these sorts of problems would be greatly appreciated. Also, is there a way to implement the fully recursive loop function without the introduction of a third parameter? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯...我认为这对你没有多大帮助,我也有点困惑,但这是我的想法。
编辑 -- 等等,我想我复制了该函数。稍后我会再考虑一下,如果我想到什么我会更新!
Uhm... I don't think this will help you much, I'm kinda baffled too, but here are my thoughts.
edit -- wait I think I miscopied the function. I'll give this more thought later, and if I think of something I'll update!