Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Python Help (basic)

  • 28-03-2014 10:05PM
    #1
    Registered Users, Registered Users 2 Posts: 1,479 ✭✭✭


    Hi,

    I am stuck on a python exercise that has me stumped. What I want to do is get the user to enter a number and then generate a 'collatz sequence' based on this. Then I want to put this sequence into a list.

    I have the first bit ok (I think)

    x = int(input())
    while x != 1:
    if x % 2 == 0:
    x = x/2
    print(x)
    else:
    x =3*x + 1
    print(x)

    So if I enter 3,

    10
    5.0
    16.0
    8.0
    4.0
    2.0
    1.0

    will appear on the screen.

    But how do I get these into a list?


Comments

  • Registered Users, Registered Users 2 Posts: 3,335 ✭✭✭padraig_f


    [B]sequence = []
    [/B]x = int(input())
    while x != 1:
       if x % 2 == 0:
          x = x/2
          print(x)
       else:
          x =3*x + 1
          print(x)
       [b]sequence.append(x)[/b]
    
    [B]print 'sequence: {0}'.format(sequence)
    [/B]
    

    Added lines in bold.


Advertisement