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!
Here is my solution. I tried to write the most “Pythonic” code that I know how to write.
Arguably, this is one of the ideal cases to use
reduceso maybeprod()should be:I don’t like to try to write one-liners where there is a reason to have more than one line. I really like the
withstatement, and it’s my habit to use that for all I/O. For this small problem, you could just do the one-liner, and if you are using PyPy or something the file will get closed when your small program finishes executing and exits. But I like the two-liner usingwithso I wrote that.I love the one-liner by @Steven Rumbalski:
Here’s how I would probably write that:
Again, for this kind of short program, your file will be closed when the program exits so you don’t really need to worry about making sure the file gets closed; but I like to make a habit of using
with.