Python 代码缩短
我试图在这里解决这个问题:- https://www.spoj.pl/problems/PHIVAL/
这些问题要求您输出尽可能多的黄金比例 (1+sqrt(5))/2 的小数位数,并尽量减少代码长度。
这就是我现在所拥有的。这段代码可以再短一点吗?
from decimal import *
getcontext().prec=7050
print(1+Decimal(5).sqrt())/2
I was trying to solve this problem here :- https://www.spoj.pl/problems/PHIVAL/
The questions asks you to output as many decimal digits of the golden ratio (1+sqrt(5))/2 as possible and also try to minimise the code length.
This is what I have right now. Can this code be made any shorter ?
from decimal import *
getcontext().prec=7050
print(1+Decimal(5).sqrt())/2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以去掉星号之前的空格。
更新:
您添加了有关无关紧要的空白的部分,因此我开始考虑一种不同的方法。如果不计算空格,您可能可以执行类似的操作
它将每个数字编码为多行字符串常量中一行上的多个空格。显然,您可以添加更多行来获得更多数字。它应该运行得相当快,因为几乎不需要进行任何计算。它使用
50(更新 2: 45)非空白字符来生成任意数量的数字输出。You can take out the space before the asterisk.
Update:
You added the part about insignificant whitespace, so I started thinking about a different approach. If whitespace isn't counted, you may be able to do something like this
It encodes each digit as a number of spaces on a line in a multi-line string constant. Obviously, you could add more lines to get more digits. It should run pretty fast, as there is very little calculation done. It uses
50(update 2: 45) non-whitespace characters to produce any number of digits output.将递归方法发挥到极致,它只使用 19 个非空白字符:
当然,生成前 1000000 个数字所需的代码长度将超过 10^1000000 个字符!
Taking
recursive
's approach to an extreme, this uses just 19 non-whitespace characters:Granted, the code required to generate the first 1000000 digits would be over 10^1000000 characters in length!
由于短代码得分高,我认为最好的方法可能就是
Due to high score for short code, i think that best approach could be just
好吧,我尝试了 javascript-ish 方法,但它显然在 Python 中不起作用:
看起来你的代码非常接近最短的解决方案。
Well I tried javascript-ish approach, and it apparently doesn't work in Python:
Looks like your code is pretty close to the shortest possible solution.