Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing shorter, readable, pythonic code

Tags:

python

I'm trying to produce shorter, more pythonic, readable python. And I have this working solution for Project Euler's problem 8 (find the greatest product of 5 sequential digits in a 1000 digit number).

Suggestions for writing a more pythonic version of this script?

numstring = ''
for line in open('8.txt'):
    numstring += line.rstrip()

nums = [int(x) for x in numstring]

best=0
for i in range(len(nums)-4):
    subset = nums[i:i+5]
    product=1
    for x in subset:
        product *= x
    if product>best:
        best=product
        bestsubset=subset

print best
print bestsubset

For example: there's gotta be a one-liner for the below snippet. I'm sure there's a past topic on here but I'm not sure how to describe what I'm doing below.

numstring = ''
for line in open('8.txt'):
    numstring += line.rstrip()

Any suggestions? thanks guys!

like image 221
dyln Avatar asked Jul 27 '12 17:07

dyln


1 Answers

I'm working on a full answer, but for now here's the one liner

numstring = ''.join(x.rstrip() for x in open('8.txt'))

Edit: Here you go! One liner for the search. List comprehensions are wonderful.

from operator import mul
def prod(list):
    return reduce(mul, list)

numstring = ''.join(x.rstrip() for x in open('8.txt'))
nums = [int(x) for x in numstring]
print max(prod(nums[i:i+5]) for i in range(len(nums)-4))
like image 78
Rob Volgman Avatar answered Sep 22 '22 12:09

Rob Volgman