开发者

Python Code Shortening

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).s开发者_运维百科qrt())/2


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

print"1."+`map(len,"""      








       """.split("\n"))`[1::3]

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.


Taking recursive's approach to an extreme, this uses just 19 non-whitespace characters:

print '1.%d'%len('                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          ')

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

print 1


Well I tried javascript-ish approach, and it apparently doesn't work in Python:

import decimal
decimal.__dict__.values()[17]().prec = 7050
...

Looks like your code is pretty close to the shortest possible solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜