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:00
def collatz(number):
    while number != 1:
        if number % 2 == 0:
            number = number // 2
            print(number)

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

try:
    num = int(input())
    collatz(num)
except ValueError:
    print('Please use whole numbers only.')

This is what I came up with on my own and based solely on what I've learned from the book so far. It took me a little bit but one of the tools I used that was invaluable to me finding my solution and has also been invaluable in learning this content is the python visualizer tool at: http://www.pythontutor.com/visualize.html#mode=edit

I was able to see what my code was doing and where it was getting hung up and I was able to continually make tweaks until I got it right.

查看更多
该账号已被封号
3楼-- · 2019-01-17 23:03

Your collatz() function should print & return only the next value. (It ends when it returns.)

The while loop should not be inside the collatz() function.

You've also got inconsistent variable names (n, number, nnumber), and some important code is commented out.

查看更多
闹够了就滚
4楼-- · 2019-01-17 23:03
import sys

def collatz(number):
if number % 2 == 0:
    result = number // 2
    print (result)

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

while result == 1:
    sys.exit

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

print ('Enter a number')

try:
    number = int(input())
    collatz(number)

except ValueError:
    print('Please enter a valid integer')
查看更多
看我几分像从前
5楼-- · 2019-01-17 23:04
def collatz(number):
    if number % 2 == 0:  # Even number
        return number // 2

    elif number % 2 == 1:  # Odd number
        return number * 3 + 1

print('Please enter a number') # Ask for the number


# Check if the number is an integer, if so, see if even or odd. If not, rebuke and exit
try:
    number = int(input())
    while number != 1:
        collatz(number)
        print(number)
        number = collatz(number)
    else:
        print('You Win. The number is now 1!')
except ValueError:
     print('Please enter an integer')

This is what I came up with for this practice exercise. It asks for an input Validates whether it's an integer. If not it rebukes and exits. If it is, it loops through the collatz sequence until the result is 1 and then you win.

查看更多
可以哭但决不认输i
6楼-- · 2019-01-17 23:06
def collatz(number):
    if number % 2 == 0:
        print(number//2)
        return number // 2
    elif number % 2 == 1:
        print(3*+number+1)
        return 3 * number + 1
r=''
print('Enter the number')
while r != int:
    try:
        r=input()
        while r != 1:
            r=collatz(int(r))
        break   
    except ValueError:
            print ('Please enter an integer')

I added input validation

查看更多
疯言疯语
7楼-- · 2019-01-17 23:07

Here's what I came up with:

import sys

def collatz(number):
    if number % 2 == 0:           # Even number
        result = number // 2
    elif number % 2 == 1:         # Odd number
        result = 3 * number + 1

    while result == 1:            # It would not print the number 1 without this loop
        print(result)
        sys.exit()                # So 1 is not printed forever.

    while result != 1:            # Goes through this loop until the condition in the previous one is True.
        print(result)
        number = result           # This makes it so collatz() is called with the number it has previously evaluated down to.
        return collatz(number)    

print('Enter a number: ')         # Program starts here!
try:
    number = int(input())         # ERROR! if a text string or float is input.
    collatz(number)
except ValueError:
    print('You must enter an integer type.')

                                  # Fully working!
查看更多
登录 后发表回答