[Tutor] syracuse sequence (collatz or hailstone)

andrade1@umbc.edu andrade1 at umbc.edu
Fri Oct 28 17:59:44 CEST 2005


hello,

Could I gather all of the values from print x into a string or a range?
Since, I am not familiar with lists yet.


def main():
        x = input("Please enter a positive starting value: ")
         while x != 1:
             if x%2 == 0:
                 x = x/2
            else:
                x = x*3+1
            print x
    print "The Syracuse sequence of your starting value is:", x

main()




----- Original Message -----
From: "Frank Bloeink" <frankbloeink at nerdshack.com>
To: <andrade1 at umbc.edu>
Sent: Friday, October 28, 2005 5:06 AM
Subject: Re: [Tutor] syracuse sequence (collatz or hailstone)


> Hey,
>
> your code seems almost alright to me, except that in your case it's only
> printing the last number of your sequence, which obviously is not what
> you want. Quick fix would be to insert a line "print x" just below else
> statement:
> ---snip--
>  else:
>    x=x*3+1
>  print x
> ---snip
> This should make clear where the error is: You are just calculating, but
> not printing the sequence!
> If you want to leave the output to the end of the program you could as
> well gather all the calculated values in a list or similar structure and
> then print the contents of the list..
>
> hth Frank
>
> On Fri, 2005-10-28 at 01:22 -0400, andrade1 at umbc.edu wrote:
> > Hello
> >
> > 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():
> >     try:
> >         x = input("Please enter a starting value: ")
> >         while x != 1:
> >
> >             if x%2 == 0:
> >                 x = x/2
> >             else:
> >                 x = x*3+1
> >
> >     except ValueError, excObj:
> >         msg = str(excobj)
> >         if msg == "math domain error":
> >             print "No negatives or decimals."
> >         else:
> >             print "Something went wrong."
> >
> >
> >
> >     print "The Syracuse sequence of your starting value is:", x
> >
> > main()
> >
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
>
>
>



More information about the Tutor mailing list