2016-03-08 32 views
1

我有代碼嘗試使用Python從列表中反轉字符串,並且無法使用傳統方法作爲練習的一部分(我不能在迭代時更改列表,但我必須遞歸執行)但我的函數沒有返回我的字符串,不知道這個問題可能是什麼:從列表中返回一個字符串

list1 = [] 

def reverse(text): 
    note = '' 
    for x in text: 
     list1.append(x) 
    print list1 

# for x in list1: 
#  note = note+list1.pop() 

    def recursive(toRev): 
     if not list1: 
       print toRev, 'Last toRev' 
       return toRev 

     else: 
       toRev = toRev+list1.pop() 
       recursive(toRev) 
     print toRev, 'Note with in the loop' 

     #recursive(toRev) 


    finalvar = recursive(note) 
    print finalvar, ' :Final' 
    return finalvar 

reverse('Python!') 
+0

你能解釋一下你更好正在試圖做的,(我認爲)轉讓的參數是什麼呢?如果目標是'reverse'('Hello')'返回''olleH'',那麼根本不需要列表或遞歸。您可以使用切片或多次記錄在SO中的內置「反轉」功能來完成此操作。 –

+2

@ Two-BitAlchemist讓學生用遞歸編寫自己的反轉函數是一個相當常見的練習。 OP在問題中提到他們不允許使用內置方法。 –

+0

謝謝仙人掌! – guyinaboxshell

回答

0

你是不是用遞歸調用的結果做任何事情,而不是通過它備份鏈。 嘗試改變recursive到:

def recursive(toRev): 
    if not list1: 
     print toRev, 'Last toRev' 
     return toRev 
    else: 
     toRev = toRev+list1.pop() 
     print toRev, 'Note with in the loop' 
     return recursive(toRev) 
+0

我明白了,這很有道理!我必須遞歸地返回到Rev,但我有更好的解決方案,謝謝你的智慧言語: – guyinaboxshell

+0

@guyinaboxshell好的,改變以符合這個要求。 – StephenTG

+0

在'return = recursive(toRev)'中輸入錯誤。 –

0

似乎你只是缺少在recursive功能return。你也應該在函數內部定義list1,而不是在它之外。

def reverse(text): 
    list1 = [] # defined inside of function 
    note = '' 
    for x in text: 
     list1.append(x) 
    #print list1 

# for x in list1: 
#  note = note+list1.pop() 

    def recursive(toRev): 
     if not list1: 
       #print toRev, 'Last toRev' 
       return toRev 

     else: 
       toRev = toRev+list1.pop() 
       return recursive(toRev) # added return 
     #print toRev, 'Note with in the loop' 

     #recursive(toRev) 


    finalvar = recursive(note) 
    #print finalvar, ' :Final' 
    return finalvar 

reverse('Python!') 
+0

非常感謝!找出了返回函數的東西。 – guyinaboxshell

0

回答感謝StephenTG

list1 = [] 

    def reverse(text): 
     note = '' 
     for x in text: 
      list1.append(x) 
     print list1 

    # for x in list1: 
    #  note = note+list1.pop() 

     def recursive(toRev): 
      if not list1: 
        print toRev, 'Last toRev' 
        return toRev 

      else: 
        toRev = toRev+list1.pop() 
        return recursive(toRev) 
        #return toRev 
      print toRev, 'Note with in the loop' 

      #recursive(toRev) 


     finalvar = recursive(note) 
     print finalvar, ' :Final' 
     return finalvar 

    reverse('Python!') 
相關問題