维持长方程的最佳方式
您认为编写此方法来计算 ackermann 函数 值的最佳方法是什么?该函数将几个“捷径”结合到最简单的计算值的方法中,通过减少递归调用量来显着加快计算速度,但最终会得到一个很长的表达式。
这些版本使用:
- 行继续符 \
- 带括号的嵌套函数
- 单个外部大括号组
您认为有哪个版本更好吗?为什么?我很好奇。
>>> def ack4(M, N):
return (N + 1) if M == 0 else \
(N + 2) if M == 1 else \
(2*N + 3) if M == 2 else \
(8*(2**N - 1) + 5) if M == 3 else \
ack4(M-1, 1) if N == 0 else \
ack4(M-1, ack4(M, N-1))
>>> def ack2(M, N):
return (N + 1) if M == 0 else (
(N + 2) if M == 1 else (
(2*N + 3) if M == 2 else (
(8*(2**N - 1) + 5) if M == 3 else (
ack2(M-1, 1) if N == 0 else
ack2(M-1, ack2(M, N-1))))))
>>> def ack3(M, N):
return ((N + 1) if M == 0 else
(N + 2) if M == 1 else
(2*N + 3) if M == 2 else
(8*(2**N - 1) + 5) if M == 3 else
ack3(M-1, 1) if N == 0 else
ack3(M-1, ack3(M, N-1)))
>>> ack2(4, 2) == ack3(4, 2) == ack4(4, 2)
True
>>>
What do you think is the best way of writing this method for calculating an ackermann function value? This function incorporates several 'short cuts' to the simplest method of calculating the value that speeds the calculation up considerably by reducing the amount of recursive calls, but you end up with a long expression.
The versions use:
- The line continuation character \
- Bracketed nested functions
- A single outer set of braces
Does any version seem better to you? why? I'm curious.
>>> def ack4(M, N):
return (N + 1) if M == 0 else \
(N + 2) if M == 1 else \
(2*N + 3) if M == 2 else \
(8*(2**N - 1) + 5) if M == 3 else \
ack4(M-1, 1) if N == 0 else \
ack4(M-1, ack4(M, N-1))
>>> def ack2(M, N):
return (N + 1) if M == 0 else (
(N + 2) if M == 1 else (
(2*N + 3) if M == 2 else (
(8*(2**N - 1) + 5) if M == 3 else (
ack2(M-1, 1) if N == 0 else
ack2(M-1, ack2(M, N-1))))))
>>> def ack3(M, N):
return ((N + 1) if M == 0 else
(N + 2) if M == 1 else
(2*N + 3) if M == 2 else
(8*(2**N - 1) + 5) if M == 3 else
ack3(M-1, 1) if N == 0 else
ack3(M-1, ack3(M, N-1)))
>>> ack2(4, 2) == ack3(4, 2) == ack4(4, 2)
True
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅仅嵌套在一个简单的 elif 链中有什么问题?
Python 代码应该对程序员来说是可读的,所以这更多的是个人选择问题。如果我必须选择你的 3 个例子之一,我会选择 ack4,因为这些反斜杠表明一切都是一个大声明,而不会像我认为的括号那样使表达式膨胀。
What's wrong with just nesting in a simple elif chain?
Python code should be readable for the programmer, so it's more of a personal choice question. If I had to pick one of your 3 examples I'd go with ack4 since those backslashes indicate that everything is one big statement without bloating the expression like a bracket does in my opinion.
不要害怕多次退货。另外,尽量避免局部变量使用大写字母。
Don't be afraid of multiple returns. Also, try to avoid capital letters for local variables.