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 1 the sequence ends
if n is even the next n of the sequence = n/2
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

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.

Also, you should be careful with integer usage in this case. I would make num a float from the get go, otherwise division operations (aka 7/2) are going to be ounded to the nearest int. You can pass floats in to your function easily:

hailstone(float(i) )

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.