[Tutor] syracuse sequence (collatz or hailstone)

andrade1@umbc.edu andrade1 at umbc.edu
Fri Oct 28 07:22:50 CEST 2005


I am trying to create a program that will calculate the syracuse sequence
which is also known as collatz or hailstone. the number that is input by
the user may be either even or odd. the number goes through a series of
functions which are x/2 if the number is even and 3x+1 if the number is
odd. it keeps doing so until the number reaches 1. An example would be if
the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence
for the value that they started with. My code currently just prints a 1
and none of the numbers that would have preceded it. any ideas on how I
could get the program to not do this would be greatly appreciated.

def main():
        x = input("Please enter a starting value: ")
        while x != 1:

            if x%2 == 0:
                x = x/2
                x = x*3+1

    except ValueError, excObj:
        msg = str(excobj)
        if msg == "math domain error":
            print "No negatives or decimals."
            print "Something went wrong."

    print "The Syracuse sequence of your starting value is:", x


More information about the Tutor mailing list