2

Please help me understand what i did wrong. The problem is

The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1.

Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)

Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.

Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1.

def collatz(number):
    if number%2==0:
        print(number//2)
    else:
        print(3*number+1)

x = int(input('print num'))
while TRUE:
    if collatz(x)!=1:
        break
AChampion
  • 29,683
  • 4
  • 59
  • 75
chris123
  • 43
  • 3
  • 1
    What makes you think you did something wrong? Tell us. We're not mind readers. – jwodder Jun 30 '18 at 02:09
  • 1
    You need to `return` the result instead of printing it. Capture that return value in a variable and then use it as the argument to your next call to `collatz` – Patrick Haugh Jun 30 '18 at 02:14
  • You need to fix your indentation, what you posted is not legal. Also, it would help you debug your own error if you printed `number` on every iteration inside the loop. – smci Jun 30 '18 at 02:14
  • *"Keep calling collatz() on that number until the function returns the value 1"* => your while-loop should be `while x != 1`, ie keep looping until x is 1. You don't need a break statement. Currently you break if the value immediately is *not* 1, which is the opposite of what you want to do – smci Jun 30 '18 at 02:15
  • @smci (re: `while != 1`), if the user enters '1', then the function will never be called. – jedwards Jun 30 '18 at 02:20
  • I fixed it to return the values, however i am confused about what should go after the while loop of x!=1. – chris123 Jun 30 '18 at 02:21
  • 1
    The indentation is wrong, you must print and return the value, you are not capturing the result of calling the function... – David Conrad Jun 30 '18 at 02:21
  • You need to read the instructions carefully. Your function has to print *and* return the new value. And you need to save the returned value so you can pass it back into the function on the next loop iteration. BTW, the Collatz conjecture is still unproven, although it has been verified for a huge range of numbers. – PM 2Ring Jun 30 '18 at 02:29
  • 1
    Possible duplicate of [Making a collatz program automate the boring stuff](https://stackoverflow.com/questions/33508034/making-a-collatz-program-automate-the-boring-stuff) – orwinmc Jun 30 '18 at 03:45
  • @jedwards: ok true for that corner case. – smci Jul 01 '18 at 08:09

4 Answers4

2

Duplicate - Making a collatz program automate the boring stuff

As others have stated in the comments, your function collatz() must return an integer also, to be fed into collatz() again.

Building off of what you have already done, we can have the function collatz_sequence(x) repeatedly call collatz() to get the desired result:

def collatz(x):
    if x % 2 == 0:
        a = x//2
    else:
        a = 3*x+1
    print(a)
    return a

def collatz_sequence(x):
    print(x)
    while x!=1:
        x=collatz(x)

Here is an example output:

>>> collatz_sequence(6)
6
3
10
5
16
8
4
2
1
orwinmc
  • 168
  • 1
  • 13
2

You must print and return in the function collatz(num):

def collatz(number):
    """prints and returns the next number in the Collatz sequence
    """
    if number % 2 == 0:
        next_collatz_number = number // 2
    else:
        next_collatz_number = 3 * number + 1
    print(next_collatz_number)
    return next_collatz_number

x = int(input('print num'))

while True:
    x = collatz(x)
    if x == 1:
        break
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

This is how I wrote the same code if you want to confront

# Write a function named collatz() that has one parameter named number. If
# number is even, then collatz() should print number // 2 and return this value.
# If number is odd, then collatz() should print and return 3 * number + 1


# Then write a program that lets the user type in an integer and that keeps
# calling collatz() on that number until the function returns the value 1.


# Add try and except statements to the previous project to detect whether the
# user types in a noninteger string. Normally, the int() function will raise a
# ValueError error if it is passed a noninteger string, as in int('puppy'). In the
# except clause, print a message to the user saying they must enter an integer.

integernuber = False
while not integernuber:

    try:
        number = int(input('Type a number: '))

        integernumber = True

    except:
        print('Please entere an integer number')

        def collatz():

            global number

            if (number % 2) == 0:
                return number / 2
                number = (number / 2)
            elif (number % 2) == 1:
                return 3 * number + 1
                number = (3 * number + 1)
            else:
                return

        while collatz() <= 1:
            number = int(collatz())
            print(number)

Hope can be helpful for you

0
try:
     number = int(input('Enter a number:'))
     while number != 1:
          number = collatz(number)
except ValueError:
     print('Enter a valid integer')

def collatz(num):
    if num % 2 == 0:
        print(str(num // 2))
        return num // 2
    else:
        print(str(3 * num + 1))
        return (3 * num + 1)

In this code, I have matched their constraint (integer constraint) and returned the value as well. I used simple recursion in the try block to get the desired output.

General Grievance
  • 4,555
  • 31
  • 31
  • 45