user1698174
user1698174

Reputation: 499

Collatz conjecture sequence

The Collatz conjecture

what i am trying to do: Write a function called collatz_sequence that takes a starting integer and returns the sequence of integers, including the starting point, for that number. Return the sequence in the form of a list. Create your function so that if the user inputs any integer less than 1, it returns the empty list [].

background on collatz conjecture:

Take any natural number n. If n is even, divide it by 2 to get n / 2, if n is odd multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1.

What I have so far:

def collatz_sequence(x):
    seq = [x]
    if x < 1:
       return []
    while x > 1:
       if x % 2 == 0:
         x= x//2
       else:
         x= 3*x+1 
    return seq

When I run this with a number less than 1 i get the empty set which is right. But when i run it with a number above 1 I only get that number i.e. collatz_sequence(6) returns [6]. I need this to return the whole sequence of numbers so 6 should return 6,3,10,5,16,8,4,2,1 in a list.

Upvotes: 9

Views: 43213

Answers (11)

kreativitea
kreativitea

Reputation: 1791

def collatz_sequence(x):
    seq = [x]
    while seq[-1] > 1:
       if x % 2 == 0:
         seq.append(x//2)
       else:
         seq.append(3*x+1)
       x = seq[-1]
    return seq

Here's some code that produces what you're looking for. The check for 1 is built into while statement, and it iteratively appends to the list seq.

>>> collatz_sequence(6)
[6, 3, 10, 5, 16, 8, 4, 2, 1]

Note, this is going to be very slow for large lists of numbers. A cache won't solve the speed issue, and you won't be able to use this in a brute-force solution of the project euler problem, it will take forever (as it does every calculation, every single iteration.)

Upvotes: 7

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 51005

You forgot to append the x values to the seq list:

def collatz_sequence(x):
    seq = [x]
    if x < 1:
       return []
    while x > 1:
       if x % 2 == 0:
         x = x // 2
       else:
         x = 3 * x + 1 
       seq.append(x)    # Added line
    return seq

Verification:

~/tmp$ python collatz.py 
[6, 3, 10, 5, 16, 8, 4, 2, 1]

Upvotes: 15

Kholdoun
Kholdoun

Reputation: 1

import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show

def collatz_sequence(N):  
  seq = [N]
  m = 0
  maxN = 0
  while seq[-1] > 1:
     if N % 2 == 0:
       k = N//2
       seq.append(N//2)
       if k > maxN:
         maxN = k
     else:
       k = 3*N+1
       seq.append(3*N+1)
       if k > maxN:
         maxN = k
     N = seq[-1]
     m = m + 1
  print(seq)

  x = np.arange(0, m+1)
  y = np.array(seq)
  xlim(0, m+1)
  ylim(0, maxN*1.1)
  step(x, y)
  show()

def collatz_exec():
  print('Enter an Integer')
  N = int(input())
  collatz_sequence(N)

This is how you can use it:

>>> from collatz_sequence import *
>>> collatz_exec()
Enter an Integer
21
[21, 64, 32, 16, 8, 4, 2, 1]

And a plot that shows the sequence:

enter image description here

Upvotes: 0

Shinjini
Shinjini

Reputation: 1

steps=0
c0 = int(input("enter the value of c0="))

while c0>1:
    if c0 % 2 ==0 :
        c0 = c0/2
        print(int(c0))
        steps +=1
    else:
        c0 = (3 * c0) + 1
        print(int(c0))
        steps +=1
print("steps= ", steps)

Upvotes: 0

AndrewK
AndrewK

Reputation: 1

Recursion:

def collatz(n):
    if n == 1: return [n]
    elif n % 2 == 0: return [n] + collatz(int(n/2))
    else: return [n] + collatz(n*3+1)

print(collatz(27))

Upvotes: 0

Lucas
Lucas

Reputation: 1

This gives all the steps of a single number. It has worked with a 50-digit number in 0,3 second.

collatz = []

def collatz_sequence(x):
    while x != 1:
        if x % 2 == 0:
            x /= 2
        else:
            x = (3*x + 1)/2
        collatz.append(int(x))

    print(collatz)

collatz_sequence()

Upvotes: 0

Tana
Tana

Reputation: 306

seq = []
x = (int(input("Add number:")))
if (x != 1):
   print ("Number can't be 1")
while x > 1:
    if x % 2 == 0:
        x=x/2
    else:
        x = 3 * x + 1
    seq.append (x)
print seq

Upvotes: 0

redx21
redx21

Reputation: 11

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

this is what i propose..

Upvotes: 0

Nisarg Lukka
Nisarg Lukka

Reputation: 1

Here's another way of doing it:

while True:
 x=int(input('ENTER NO.:'))
 print ('----------------')
 while x>0:
  if x%2==0:
   x = x/2
  elif x>1:
   x = 3*x + 1
  else:
   break
   print (x)

This will ask the user for a number again and again to be put in it until he quits

Upvotes: 0

ShivaGuntuku
ShivaGuntuku

Reputation: 5475

def collataz(number):
    while number > 1:
        if number % 2 == 0 :
            number = number //2
            print(number)
        elif number % 2 ==1 :
            number = 3 * number + 1
            print(number)
        if number == 1 :
            break

print('enter any number...!')
number=int(input())
collataz(number)

Upvotes: -1

Jose
Jose

Reputation: 134

seq = []

def collatz_sequence(x):
    global seq
    seq.append(x)
    if x == 1:
        return 
    if (x % 2) == 0:
        collatz_sequence(x / 2)
    else:
        collatz_sequence((x * 3) + 1)

collatz_sequence(217)
print seq

Upvotes: -1

Related Questions