1

Here is a small piece of code I have for working on a programming puzzle from Project Euler. I'm reading in a file of 1,000 digits and trying to find the 13 adjacent ones that have the largest product. The problem is that the line max_prod = prod_over_str(s) doesn't set max_prod to the return value of prod_over_str but instead a function and running the script causes an error in the statement if prod_over_str(s) > max_prod because somehow prod_over_str(s) is an int yet max_prod a function. Yet if I print the value of prod_over_str(s) to the screen it's a number. How can I fix this?

def prod_over_str(s):
    prod = 1
    for c in s:
        prod *= int(c)
    return prod

with open('/path/text.txt') as f:
    s = f.read(13)
    max_prod = prod_over_str(s)

    while True:
        c = f.read(1)
        if not c:
            break
        s = s[1:] + c
        if prod_over_str(s) > max_prod:
            max_prod = prod_over_str

Here is the Traceback:

In [18]: %run problem8.py
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/dsaxton/Desktop/Python/project_euler/problem8.py in <module>()
     14             break
     15         s = s[1:] + c
---> 16         if prod_over_str(s) > max_prod:
     17             max_prod = prod_over_str
     18 

TypeError: unorderable types: int() > function()
6
  • 2
    How about changing str to another variable name, say my_str to avoid shadowing built-in method str Commented Jan 1, 2016 at 20:32
  • What kind of error does your script produce? Give a full stacktrace please. Commented Jan 1, 2016 at 20:33
  • Does it make any difference doing so? Commented Jan 1, 2016 at 20:35
  • 1
    In your last line you're assigning max_prod = prod_over_str. prod_over_str is a function, so max_prod will be assigned that function. It should probably read max_prod = prod_over_str(s). Commented Jan 1, 2016 at 20:36
  • @karlson Ah yes, that was the problem. Thanks a lot. Commented Jan 1, 2016 at 20:38

1 Answer 1

6

Your error is actually in the line below the if statement:

if prod_over_str(s) > max_prod: 
    max_prod = prod_over_str

First you check the return value of the function and then you assign the function itself to max_prod.

You need to do something like this:

if prod_over_str(s) > max_prod:
     max_prod = prod_over_str(s)

Or:

prod = prod_over_str(s)
if prod > max_prod: 
    max_prod = prod
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I had overlooked that. Thanks for the help.
Mark as answered then!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.