Making a collatz program automate the boring stuff

2019-01-17 22:42发布

I'm trying to write a collatz program using the guidelines from a project found at the end of chapter 3 of Automate the Boring Stuff with Python. I'm using python 3.4.0. Here's the project outline:

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.

The output of this program could look something like this: Enter number: 3 10 5 16 8 4 2 1

I am trying to make a function that uses if and elif statements within a while loop. I want the number to print, and then return to the beginning of the loop and reduce itself to one using the collatz sequence, with each instance of a resulting number being printed as it goes through the loop. With my current code, I'm only able to print the first instance of the number, and that number does not go through the loop after that. Here's my code:

#collatz

print("enter a number:")
try:
    number = (int(input()))
except ValueError:
          print("Please enter a valid INTEGER.")


def collatz(number):
    while number != 1:

        if number % 2==0:
            number = (number//2)
            #print(number)
            return (print(int(number)))

        elif nnumber % 2==1:
            number = (3*number+1) 
            #print(number)
            return (print(int(number)))

        continue


collatz(number)

20条回答
孤傲高冷的网名
2楼-- · 2019-01-17 23:14

Here's my 19 lines:

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


number = 0
while number == 0:
    try:
        number = int(input('Please enter a number: '))
        if number == 0:
            print('Number must be an integer not equal to zero.')
        else:
            while True:
                number = collatz(number)
                print(number)
                if abs(number) == 1 or number == -5 or number == -17: 
                    break #Collatz seq ends/enters recurring loop when number hits -17, -5, -1 or 1
    except ValueError:
        print('Number must be an integer.')
查看更多
地球回转人心会变
3楼-- · 2019-01-17 23:16
def collatz(number):
    if number % 2 == 0:
        return number // 2
    elif number % 2 == 1:
        return 3 * number + 1

try:
    chosenInt = int(input('Enter an integer greater than 1: '))

    while chosenInt < 2:
        print("Sorry, your number must be greater than 1.")
        chosenInt = int(input('Enter an integer greater than 1: '))

    print(chosenInt)

    while chosenInt != 1:
        chosenInt = collatz(chosenInt)
        print(chosenInt)

except ValueError:
    print('Sorry, you must enter an integer.')
查看更多
别忘想泡老子
4楼-- · 2019-01-17 23:17

My Code

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

try:
    print ('Enter the number to Collatz:')
    collatz(int(input()))
except ValueError:
    print('Enter a valid integer')
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-17 23:17

Something that helped me a lot in this stage of my learning is understanding that a function should have a well-defined purpose, and adding a loop into the function dilutes that.

Here is my solution (someone helped me work on this and addressed the same mistakes I see in your code):

def collatz(number): # defining the function here. The function takes 1 argument - number.

    if number % 2 == 0: # if statement where we say that if the remainder of number by 2 is 0, then its an even number.
        even = number // 2 # assign number divided by two to a variable named even.
        print(even) # displaying that even value.
        return even # return that value.
    else: # else if number is not even.
        odd = 3 * number + 1 # then it is an odd number, and if it is an odd number then we will multiple that number by 3 and add 1.
        print(odd) # printing the odd number
        return odd # return that value

try:
    number = int(input('please enter a number:')) # number is an input from a user and here we ask the user for what input
except ValueError:
    print('Error, you must enter an integer.')


while number !=1: # while loop states that while the value of number does not equal 1...
       number = collatz(number) # ... assign the output of the collatz() function as a new value of the number, and run the collatz() function again.
查看更多
6楼-- · 2019-01-17 23:21
def collatz(number):
    if(number%2==0):
        n=number//2
        print(n)
        return n
    else:
        ev=3*number+1
        print(ev)
        return ev
num1=input("Enter a number: \n")

try:
    num= int(num1)
    if(num==1):
        print("Enter an integer greater than 1")
    elif(num>1):
        a=collatz(num) 
        while(True):
            if(a==1):
                break
            else:
                a=collatz(a)
    else:
        print("Please, Enter a positive integer to begin the Collatz sequence")

except:
    print("please, Enter an integer")

Try to came up with a solution based on up to chapter Function from automate the boring stuff. If need help related to Collatz Problem, then visit here: http://mathworld.wolfram.com/CollatzProblem.html

查看更多
爷、活的狠高调
7楼-- · 2019-01-17 23:23
def collatz(number):

    if number % 2 == 0:
        print(number // 2)
        return number // 2

    elif number % 2 == 1:
        result = 3 * number + 1
        print(result)
        return result

n = input("Give me a number: ")
while n != 1:
    n = collatz(int(n))

Output:

Give me a number: 3 10 5 16 8 4 2 1

Give me a number: 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

查看更多
登录 后发表回答