我正在尝试使用Python自动化无聊的第3章末尾的项目指南编写Collatz程序。我正在使用python 3.4.0
。以下是项目大纲:
编写一个名为collatz()
的函数,该函数有一个名为number的参数。如果数字是偶数,则collatz()
应打印number // 2
并返回此值。如果数字为奇数,则应打印collatz()
并返回3 * number + 1
。然后编写一个程序,让用户输入一个整数,并在该数字上保持调用collatz()
,直到函数返回值1
。
此程序的输出可能如下所示:
Enter number: 3 10 5 16 8 4 2 1
我正在尝试创建一个在while循环中使用if
和elif
语句的函数。我希望打印数字,然后返回到循环的开头,并使用Collatz序列将其自身缩减为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)
答案 0 :(得分:15)
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
答案 1 :(得分:5)
这是我想出的:
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!
答案 2 :(得分:3)
您的collatz()
功能应打印&只返回下一个值。 (它在返回时结束。)
while
循环不应位于collatz()
函数内。
您还获得了不一致的变量名称(n
,number
,nnumber
),并且注释了一些重要的代码。
答案 3 :(得分:2)
我为同一练习编写的17行代码。
def collatz(number):
""" check if the number is even or odd and performs calculations.
"""
if number % 2 == 0: # even
print(number // 2)
return number //2
elif number % 2 != 0: # odd
result = 3*number+1
print(result)
return result
try:
n = input('Enter number: ') # takes user input
while n !=1: # performs while loop until 'n' becomes 1
n = collatz(int(n)) # passes 'n' to collatz() function until it arrives at '1'
except ValueError:
print('Value Error. Please enter integer.')
答案 4 :(得分:0)
在你的程序(问题)中,执行return语句后,不执行continue。所以它只会循环一次迭代。
您的程序不适用于输入整数 1。您可能想用 1 来检查方法的结果,而不应该在开始时检查用户输入本身。 1 也是程序的有效输入。
首选方法是执行一项操作。 (SOLID 编程原则)。最好在循环中调用函数而不是在函数内部循环。增加了方法的可重用性。
def collatz(number):
if number % 2 == 0:
print(number // 2) # logically, floor division is equivalent to division when even number with 2
return number // 2
elif number % 2 != 0:
print(number * 3 + 1)
return number * 3 + 1
number = int(input("Please enter a number\n"))
result = collatz(number) # this way the program also takes 1 as input
while result != 1:
result = collatz(result)
# Output:
Please enter a number
1
4
2
1
Please enter a number
32
16
8
4
2
1
答案 5 :(得分:0)
您可以简单地尝试一下
while True:
number=int(input('Enter next positive number or 0 to quit: '))
iteration=0
currentNumber=0
item=1
sumOfNumbers=0
print(number,end=' ')
if(number):
while currentNumber !=1 :
currentNumber=int(number/2) if(number%2==0) else number*3+1
number=currentNumber
iteration +=1; item +=1
sumOfNumbers +=currentNumber
print(currentNumber,end ='\n' if(item %5==0) else ' ')
print('\nIt took ',iteration,'iterations to arrive at 1')
print('The average is ',round((sumOfNumbers/iteration),2))
else :
break
答案 6 :(得分:0)
def cyclic(number):
if number % 2 == 0:
if number // 2 == 1:
print(1)
else:
print(number//2)
cyclic(number // 2)
else:
print((number * 3) + 1)
cyclic((number * 3) + 1)
print("Enter a number:")
try:
n = int(input())
cyclic(n)
except ValueError:
print("Unvalied value")
最简单的一个
答案 7 :(得分:0)
我很难理解这项练习的逻辑。 但是我不知道如果数字为负,我会怎么做才能显示错误。
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
while True:
try:
entry = input('enter a positive number: ')
while entry != 1:
entry = collatz(int(entry))
# if we have a negative number
while entry < 1:
break
except ValueError:
print('Error, enter valid number')
答案 8 :(得分:0)
14行:
不明白为什么我们需要“ elif number%2 == 1”而不是简单的“ else”吗?
def collatz(number):
while number != 1:
if number %2 == 0:
number = number/2
print(number)
else:
number = 3*number+1
print(number)
print('Enter a number')
try:
number = (int(input()))
except ValueError:
print("Please enter an INTEGER.")
collatz(number)
答案 9 :(得分:0)
我已经添加了try,除了这样(有休息)
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
n = input("Give me a number: ")
while n != 1:
try:
isinstance(n, int)
n = collatz(int(n))
except:
print('Error: Invalid argument.')
break
答案 10 :(得分:0)
我设法在不使用任何return语句的情况下正确地完成了该任务,并在函数内部嵌套了while循环。
number=int(input('Enter number:\n'))
def collatz(number):
while number !=1:
if number% 2 == 0:
number= number//2
print(number)
else:
number= 3 * number + 1
print(number)
collatz(number)
答案 11 :(得分:0)
我认为这个解决方案对于学习者来说可能比接受的解决方案更简单:
def collatzSequence(number):
if (number % 2 == 0): # if it's even
number = number // 2
else: # if it's odd
number = number * 3 + 1
print (number)
return (number)
n = int(input('Enter a number: '))
while (n != 1):
n = collatzSequence(n)
结果将是这样的:
Enter a number: 5
16
8
4
2
1
答案 12 :(得分:0)
这是我的19行:
<div class="row rowdiv" ng-repeat="comit in comits" ng-if="$index % 2 == 0">
<div class="col-md-6">
<img ng-src="{{comits[$index].urlToImage}}" alt="">
<h3><a ng-href="{{comits[$index].url}}">{{comits[$index].title}}</a></h3>
<p>{{comits[$index].description}}</p>
<h5>{{result}} {{comits[$index].author}}</h5>
<h6 class="pull-right">{{comits[$index].publishedAt}}</h6>
</div>
<div class="col-md-6">
<img ng-src="{{comits[$index +1].urlToImage}}" alt="">
<h3><a ng-href="{{comits[$index +1].url}}">{{comits[$index +1].title}}</a></h3>
<p>{{comits[$index + 1].description}}</p>
<h5>{{result}} {{comits[$index + 1].author}}</h5>
<h6 class="pull-right">{{comits[$index +1].publishedAt}}</h6>
</div>
</div>
答案 13 :(得分:0)
def collatz(number):
if number%2==0:
return number//2
elif number%2==1:
return number*3+1
step=1 #counter variable for amusement and seeing how many steps for completion.
try: #in case of ValueError
number=int(input('Enter a Number for Collatz Sequencing:'))
while collatz(number)!=1:
print(collatz(number))
number=int(collatz(number))
if collatz(number)!=1:
print('Calculating step ' + str(step) + '.')
step=step+1
else:
print ('Calculating step ' +str(step) + '.')
print('1 Has Been Reached.')
except ValueError:
print('Enter an Integer please:')
答案 14 :(得分:0)
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.')
答案 15 :(得分:0)
def collatz(number):
while number != 1:
if number %2==0:
number = number//2
yield number
elif number %2 ==1:
number=number*3 +1
yield number
while True:
try:
for n in collatz(int(input('Enter number:'))):
print(n)
break
except ValueError:
print('Please enter an integer')
额外的True循环将帮助程序在用户输入非整数后继续运行。
答案 16 :(得分:0)
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')
答案 17 :(得分:0)
我正在阅读相同的课程,我做了一个很长的解决方案(当我学习一些新的东西时改进它)。我建议你随着章节的进展及其良好的培训,及时更新你的文件。我的字符串操作现在保存到\ collatzrecords.txt!
我通过使用递归(一个方法调用自身)解决了核心问题:
def autocollatz(number):
global spam
spam.append(number)
if number % 2 == 0:
autocollatz (int(number/2))
elif number % 2 == 1 and number != 1:
autocollatz(int(number*3+1))
垃圾邮件是我列出的所有值的数字&#34;看到&#34;在前往1的路上。 正如你所看到的,当数字是偶数时,方法被称为agin,数字为/ 2。如果数字是偶数,则用数字* 3 + 1调用。
修改了数字== 1检查了一下。我希望它可以节省计算时间 - 我已经达到了23 000 000! (当前记录为15 733 191,其中704步为1)
答案 18 :(得分:0)
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")
尝试提出一个基于章节功能的解决方案来自动化无聊的东西。 如果需要有关Collatz问题的帮助,请访问: http://mathworld.wolfram.com/CollatzProblem.html
答案 19 :(得分:0)
此线程上的每个解决方案都缺少一件事:如果用户输入“1”,该函数仍应运行Collatz序列的计算。我的解决方案:
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')
答案 20 :(得分:0)
ORDER BY
我添加了输入验证
答案 21 :(得分:0)
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')
这就是我为这次练习所提出的。 它要求输入 验证它是否为整数。如果没有,它会谴责并退出。如果是,它会循环通过collatz序列,直到结果为1,然后你就赢了。
答案 22 :(得分:0)
我的代码
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')
答案 23 :(得分:0)
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)
答案 24 :(得分:0)
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.')
这是我自己提出的,完全基于我迄今为止从本书中学到的东西。它花了我一点点,但我使用的工具之一对于我找到我的解决方案是非常宝贵的,并且在学习这些内容方面也非常宝贵,它是python可视化工具:http://www.pythontutor.com/visualize.html#mode=edit
我能够看到我的代码在做什么以及它挂在哪里,我能够不断进行调整,直到我做对了。
答案 25 :(得分:0)
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 != 1:
n = collatz(int(n))
except ValueError:
print('whoops, type an integer, bro.')
答案 26 :(得分:-1)
在我学习的这个阶段帮助我很多的东西是理解一个函数应该有一个明确定义的目的,并且在函数中添加一个循环会稀释它。
这是我的解决方案(有人帮我解决了这个问题并解决了我在代码中看到的同样错误):
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.