各种显示模式的递归Collat​​z

时间:2016-12-03 05:52:01

标签: python recursion

我有一项任务的以下信息:

## CollatzRecursion


###
# define your RECURSIVE version of Collatz below this comment so that it runs
# correctly when called from below.
#
# 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 or external 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 :(得分:0)

不,你不能使用列表(或任何其他类型的数组)因为指令告诉你“你的Collat​​z函数不能使用任何其他内部或外部变量”。该限制也是一个提示:您需要在递归期间的适当时间打印Collat​​z序列值。

如果不为您编写代码,很难给出进一步的提示,我知道您不希望这样。但是这里有一个版本以自然生成的顺序打印序列,并且通过一些关于递归如何工作的思考,您应该能够弄清楚如何修改它以便以相反的顺序打印序列。一旦你完成了这项工作,很容易让它顺利完成。

def collatz(m):
    print m,
    if m > 1:
        collatz(3 * m + 1 if m % 2 else m // 2)

# test

collatz(7)
print    

<强>输出

7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

P.S。你的老师应该教你Python 3,因为在2020之后将不再支持Python 2。