在Python 2.7中使用递归和多个参数实现Collatz猜想
我需要写一段Python代码来实现“科拉兹猜想”,这个过程需要用到递归。用户会被要求输入一个正整数,然后这个数字会根据以下规则进行处理:如果是偶数,就除以2;如果是奇数,就乘以3再加1。这个过程会一直进行,直到数字变成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
1 个回答
0
首先,你现在的方法并不是题目要求的递归方法。
我个人会这样做(符合递归的要求,并且不需要额外的变量):
def collatz(acc, mode):
if isinstance(acc, int):
acc = [acc]
if acc[-1] == 1:
if mode not in 'FBP':
raise Exception('Unsupported display type')
if mode == 'F':
print ''.join(map(str, acc))
elif mode == 'B':
print ''.join(map(str, acc[::-1]))
else:
print ''.join(map(str, acc + acc[::-1]))
return
collatz(acc + [acc[-1] * 3 + 1 if acc[-1] % 2 else acc[-1] / 2], mode)
示例用法:
>>> collatz(11, 'F')
1134175226134020105168421
>>> collatz(11, 'B')
1248165102040132652173411
>>> collatz(11, 'P')
11341752261340201051684211248165102040132652173411