[Tutor] syracuse sequence (collatz or hailstone)
kent37 at tds.net
Fri Oct 28 12:02:29 CEST 2005
andrade1 at umbc.edu wrote:
> 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
Above you have a loop. Each time through the loop you change the value of x. You don't retain the old value of x so it is lost. The simplest thing would be to print x in the loop so each successive value is shown to the user.
> 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
> Tutor maillist - Tutor at python.org
More information about the Tutor