dsaxton
dsaxton

Reputation: 1015

Python function not evaluating

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()

Upvotes: 1

Views: 285

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

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

Upvotes: 6

Related Questions