我需要使用递归为 collatz 猜想编写 python 代码,其中提示用户输入一个正整数,如果偶数乘以 3,则该数字除以 2,如果奇数则加 1,并且此序列一直持续到值等于一。我还必须提示用户选择如何显示序列,无论是标准的计算方式、反转方式还是回文方式(向前和向后,即 86324895159842368) 以下是我目前所拥有的。我计算序列本身没有问题,但我不确定如何实现第二个参数。每当我尝试将方向定义为 F、B 或 P 时,都会出现一堆错误。在我需要去的地方的任何帮助将不胜感激
## CollatzRecursion
###
# define your RECURSIVE version of Collatz below this comment so that it runs
# correctly when called from below.
def Collatz(m):
seq = [m]
if m < 1:
return []
while m > 1:
if m % 2 == 0:
m = m / 2
else:
m = 3 * m + 1
seq.append(m)
if displaymode (F) :
return seq
if displaymode (B) :
seq = seq[::-1]
return seq
if displaymode (P) :
#
# REQUIREMENTS:
# a) The correct sequence must be printed, all the values on one line.
# b) Your Collatz function must use recursion.
# c) Aside from two arguments accepting a positive integer value and the letter
# F, B, or P; your Collatz function MAY NOT use any other internal variables.
# d) Your Collatz function may accept only the two arguments described in (c).
# e) If the second argument is 'F', the sequence should b printed in its
# naturally generated order.
# If the second argument is 'B', the sequence should be printed in reverse.
# If the second argument is 'P', then a palindrome of the sequence values should
# be printed (see http://en.wikipedia.org/wiki/Palindrome). In this case
# it doesn't matter if your function prints the first value as 1 or the
# value provided by the user.
###
###
# Do NOT alter Python code below this line
###
m = input( "Enter a positive integer value: " )
displaymode = '' # initialize to anything not F, B, P
while displaymode not in ['F', 'B', 'P'] :
displaymode = raw_input( "Choose a display mode: F=forward, B=backward, P=palindrome: " )
Collatz( m, displaymode )
print