Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).sqrt())/2
like image 542
jack_carver Avatar asked Apr 18 '11 15:04

jack_carver


People also ask

How do you shorten long code in Python?

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.

What makes a code Pythonic?

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.


2 Answers

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.

like image 71
recursive Avatar answered Sep 29 '22 18:09

recursive


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!

like image 36
Daniel Lubarov Avatar answered Sep 29 '22 19:09

Daniel Lubarov