2016-12-03 48 views
0

我有一個分配的以下信息:遞歸在Collat​​z隨着各種顯示模式

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

我不確定我怎麼能啓動這個問題,但我想這將涉及序列中添加值一個數組,以便它們可以向後打印並作爲迴文。我只想給我一些指點/建議,讓我開始。謝謝!

回答

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的像Python 2將2020年

後不再支持