0

This function, that I got from this question, is as follows:

def f(n, p, k, t):
    return sum(sum(1 if n == 3 else
                   (0 if k == 1 else
                    (1/36) * f(n-1, p, k-1, t-(max(p,i)))
                    for i in xrange(1, 7)))
                   for p in xrange(1, 7))

print sum(f(5,j,3,15) for j in xrange(1, 7))

When I run this, I get this long traceback error sequence ending in:

File "C:/Users/r/Documents/school/IB/Computer Science HL/Other Languages/Problem240/Problem240 - recursive2.py", line 6, in <genexpr>
for p in xrange(1, 7))
TypeError: 'int' object is not iterable

Can someone please tell me what's going on? What is wrong with my code and how would I fix it? Thank you!

2
  • 3
    I have a feeling that it's about the parenthesis Commented Feb 21, 2013 at 0:44
  • 2
    There really is no reason to write this as one giant expression. Are you just looking for "what did I get wrong here?" or "How can I organize this in a way that's readable enough for me to debug myself?" Commented Feb 21, 2013 at 0:47

2 Answers 2

2

i think you mean

def f(n, p, k, t):
    return sum(sum(1 if n == 3 else
                   (0 if k == 1 else
                    (1/36) * f(n-1, p, k-1, t-(max(p,i)))) # <- more here
                   for i in range(1, 7)) # <- less here
               for p in range(1, 7))

print(sum(f(5,j,3,15) for j in range(1, 7)))

(i'm using python 3, but it's basically the same).

you have some parens wrong so the inner sum isn't a generator expression like you expect.

also see gnibbler's point below since you're using python 2

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I knew it was the problem with the parentheses. I just put the extra one in the wrong place. :D
(1.0/36) for Python2 to force float division
1

If you can't understand your own code, break it down into smaller parts

def f(n, p, k, t):
    ternary = (1 if n == 3 else 0 if k == 1 else 
        f(n-1, p, k-1, t-max(p,i))/36.0 for i in range(1, 7))

    inner_sum = sum(ternary)
    return sum(inner_sum for p in range(1, 7))

Comments

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.