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
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
Pythonic code is just a description of a code that's easy to read, follow and understand. If you follow these rules, you'll be considered fluent in Python. In order to be fluent in Python you'll need to use idioms — to write Pythonic code. The only way to do that is to practice.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With