2012-11-02 71 views
0

我被要求創建一個程序,我已完成後,我做的是一個遞歸版本。 它的意義不大,它的鞋帶串起來。這裏是它的版本是我寫的,誰能告訴我如何做一個遞歸程序出來呢?遞歸編程殘端?

def laceStrings(s1, s2): 
    """ 
    s1 and s2 are strings. 

    Returns a new str with elements of s1 and s2 interlaced, 
    beginning with s1. If strings are not of same length, 
    then the extra elements should appear at the end. 
    """ 
    join = [] 
    smaller = min(s1, s2, key=len) 
    for num in range(len(smaller)): 
     join.append(s1[num]) 
     join.append(s2[num]) 
    join = ''.join(join) 
    if len(s1) != len(s2): 
     smaller = len(smaller) 
     join = join + max(s1, s2, key=len)[smaller:] 
    return join 

編輯:我的朋友給了我這個模板,但我仍然無法弄清楚。誰能幫忙?

def laceStringsRecur(s1, s2): 
    """ 
    s1 and s2 are strings. 

    Returns a new str with elements of s1 and s2 interlaced, 
    beginning with s1. If strings are not of same length, 
    then the extra elements should appear at the end. 
    """ 
    def helpLaceStrings(s1, s2, out): 
     if s1 == '': 
      #PLACE A LINE OF CODE HERE 
     if s2 == '': 
      #PLACE A LINE OF CODE HERE 
     else: 
      #PLACE A LINE OF CODE HERE 
    return helpLaceStrings(s1, s2, '') 
+0

我認爲這是一個完全可以接受的問題。 thg435的回答顯示它相當有責任感。投票重新開放。 –

回答

5

引述wikipedia

遞歸函數定義具有一個或多個基站的情況下,意味着輸入(S)的量,功能產生的結果平凡(不重複),以及一個或多個遞歸情況下,意味着輸入(S)的量,程序重複(調用自身)。

這裏,基本情況如下(假設A和B是參數字符串):

if one of A or B is empty -> return the other string 

和遞歸情況:

split each of A, B into the first char and the rest (eg. XYZ => X, YZ) 
    (recursive call) S = interlaced version of rest(A),rest(B) 
    return first-char(A) + first-char(B) + S 

讓我們知道,如果你有問題把它翻譯成python。

5
def laceStringsRecur(s1, s2): 

    """ 
    s1 and s2 are strings. 

    Returns a new str with elements of s1 and s2 interlaced, 
    beginning with s1. If strings are not of same length, 
    then the extra elements should appear at the end. 
    """ 
    def helpLaceStrings(s1, s2, out): 
     if s1 == '': 
      #PLACE A LINE OF CODE HERE 
      return out+s2 
     if s2 == '': 
      #PLACE A LINE OF CODE HERE 
      return out+s1 
     else: 
      #PLACE A LINE OF CODE HERE 
      return helpLaceStrings(s1[1:], s2[1:], out+s1[0]+s2[0]) 
    return helpLaceStrings(s1, s2, '')