2014-04-23 77 views
0

我需要使用遞歸爲collat​​z猜想編寫python代碼,其中提示用戶輸入正整數,如果偶數乘以3,則該數字除以2並且如果奇數則加1,並且該序列繼續,直到該值等於1。我還必須提示用戶選擇如何顯示序列,無論是計算,顛倒或作爲迴文的標準方式(向前和向後,即86324895159842368)。下面是我現在所擁有的。我沒有計算序列本身的問題,但我不知道如何實現第二個參數。任何時候我試圖將方向定義爲F,B或P,我都會遇到一些錯誤。任何幫助,我需要去與此將不勝感激使用遞歸和python中的多個參數的collat​​z猜想2.7

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

着:'「」。加入( str(x)代表Collat​​z(m)中的x)',向後:'''.join(str(x)代表x在反向(Collat​​z(m)))'',迴文:'a =''.join(str (x)對於Collat​​z(m)中的x)\ n打印a +反向(a)'\ – njzk2

+0

如果您有錯誤,則應提供回溯 – jonrsharpe

回答

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 
相關問題