使 collat​​z 程序自动化无聊的东西 [英] Making a collatz program automate the boring stuff

查看:26
本文介绍了使 collat​​z 程序自动化无聊的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用《使用 Python 自动化无聊的东西》第 3 章结尾处的项目指南编写 Collat​​z 程序.我正在使用 python 3.4.0.以下是项目大纲:

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:

编写一个名为 collat​​z() 的函数,它有一个名为 number 的参数.如果数字是偶数,那么 collat​​z() 应该打印 number//2 并返回这个值.如果数字是奇数,则 collat​​z() 应该打印并返回 3 * number + 1.然后编写一个程序,让用户输入一个整数,并在该数字上不断调用 collat​​z(),直到函数返回值 1.

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

该程序的输出可能如下所示:

The output of this program could look something like this:

Enter number: 3 10 5 16 8 4 2 1 

我正在尝试创建一个在 while 循环中使用 ifelif 语句的函数.我想要打印数字,然后返回到循环的开头,并使用 Collat​​z 序列将自身减少为 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. Following is 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)

推荐答案

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

输出:

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

这篇关于使 collat​​z 程序自动化无聊的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆