Python 使 collat​​z 程序自动化无聊的东西

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33508034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:28:26  来源:igfitidea点击:

Making a collatz program automate the boring stuff

pythonpython-3.4

提问by DeltaFlyer

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. Following is the project outline:

我正在尝试使用在《使用 Python 自动化无聊的东西》第 3 章末尾找到的项目中的指导方针编写 Collat​​z 程序。我正在使用 python 3.4.0。以下是项目大纲:

Write a function named collatz()that has one parameter named number. If the number is even, then collatz()should print number // 2and return this value. If the 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.

编写一个collatz()名为 number的函数,该函数具有一个名为 number 的参数。如果数字是偶数,collatz()则应打印number // 2并返回此值。如果数字是奇数,collatz()则应打印并返回3 * number + 1。然后编写一个程序,让用户输入一个整数,并不断调用collatz()该数字,直到函数返回该值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 ifand elifstatements 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. Following is my code:

我正在尝试创建一个在 while 循环中使用ifelif语句的函数。我想要打印数字,然后返回到循环的开头,并使用 Collat​​z 序列将其自身减少到 1,结果数字的每个实例在通过循环时都会被打印出来。使用我当前的代码,我只能打印数字的第一个实例,并且此后该数字不会通过循环。以下是我的代码:

#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)

采纳答案by Nuncjo

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

回答by Jonathan Clede

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

您的collatz()函数应该只打印并返回下一个值。(它返回时结束。)

The whileloop should not be inside the collatz()function.

while循环不应该是内部的collatz()功能。

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

您还得到了不一致的变量名 ( n, number, nnumber),并且一些重要的代码被注释掉了。

回答by doc_gunthrop

Nuncjo got the solution that works. I tweaked it a little to add try and except statements for error handling.

Nuncjo 得到了有效的解决方案。我稍微调整了一下以添加 try 和 except 语句以进行错误处理。

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

try:
    n = input("Enter number: ")
    while n > 0 and n!= 1:
        n = collatz(int(n))
except ValueError:
    print('whoops, type an integer, bro.')

回答by Ryan Hallberg

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

这是我自己提出的,完全基于我迄今为止从书中学到的知识。我花了一点时间,但我使用的其中一个工具对我找到我的解决方案非常宝贵,并且在学习此内容时也非常宝贵,那就是 python 可视化工具,网址为:http: //www.pythontutor.com/visualize.html #mode=编辑

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.

我能够看到我的代码在做什么以及它在哪里被挂断,并且我能够不断地进行调整,直到我做对了。

回答by Maecenas

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

while True:
    try:
    number = int(input('Enter a positive integer.'))  
    if number <= 0: 
        continue
    break
except ValueError: 
    continue


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

回答by Jebin

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')

回答by ubundows

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!

回答by Christopher Wales

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.

这就是我为这次练习而想到的。它要求输入验证它是否是一个整数。如果不是,它会斥责并退出。如果是,它会循环遍历 collat​​z 序列,直到结果为 1,然后您就赢了。

回答by Lukyanov Mikhail

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

我添加了输入验证

回答by stevensonmt

Every solution on this thread is missing one thing: if the user inputs "1" the function should still run the computations of the Collatz sequence. My solution:

此线程上的每个解决方案都缺少一件事:如果用户输入“1”,该函数仍应运行 Collat​​z 序列的计算。我的解决方案:

def collatz(number):
    while number == 1:
        print("3 * " + str(number) + " + 1 = " + str(3*number+1))
        number = 3*number+1 ##this while loop only runs once if at all b/c at end of it the value of the variable is not equal to 1
    else:
        while number != 1:
            if number % 2 == 0:
                print(str(number) + ' // 2 = ' + str(number//2))
                number = number//2
            else:
                print("3 * " + str(number) + " + 1 = " + str(3*number+1))
                number = 3*number+1

 print('Please input any integer to begin the Collatz sequence.')

while True:
    try:
        number = int(input())
        collatz(number)
        break
    except ValueError:
        print('please enter an integer')