Hi, so im writting a Python program, and ive hit a spot of bother

"TypeError: unsupported operand type(s) for %: 'list' and 'int'"

# if n is odd then the next n of the sequence = (3*n)+1

``````def hailstone(num):
length = 1
while num != 1:
print num, "===>>",
if num % 2 != 0:
num = 3 * num + 1
else:
num = num / 2
length = length + 1
print num,
print ("; length = %d") % length
return length()

print hailstone(range(0,100))
``````

I am trying to get the code to print out the first 100 values with their lengths!
All help is appreciated! thanks

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span

Your function takes an integer, but you are passing in a list. If you print range(0,100), you will see that this is one object; a list of numbers. Instead, you should pass them one by one, or adjust your function to take in a list of numbers.

``````for i in range(0,100):
print hailstone(i)
``````

Forgive me I'm not too good with python, but would really like to understand - so how do i adjust my function to take in a list of numbers?

Also you can not use integer valued variable length as function like you are doing at line 12.

Try this:

``````def hailstone(start):

num = start

length = 1

while num != 1:

if num % 2 != 0:

num = 3 * num + 1

else:

num = num / 2

length += 1

return (start, length)

for i in range(0,100):
print hailstone(i)
``````

I changed your function so that it remembers the starting value, and then changed the return to send back the starting value and the associated length. Let me know if it works, I can't test it on this computer i'm at right now. Sorry if the formatting is messed up, using crappy windows wordpad.