1

宿題の質問の場合、各項目を 1 つずつインクリメントするリストから項目を印刷したいと考えています。再帰を使用してこれを行いたいです(理想的にはリストを変更せずに)。

注: 再帰が Python やその他の言語の標準的な解決策ではないことは理解しています (実際の Python 実装では使用するつもりはありません) が、これは CS コースの再帰セクションの一部です。

この問題は、単純なループを使用することで、はるかに簡単に、より Pythonic な方法で解決できると思いforます (リスト内包表記はまだ学習していません)。

def iter_increment(p):
    for n in p:
        print n + 1

print iter_increment([1,2,3,4])

これを再帰的に解決するために、リストのコピーを作成しました。

def rec_increment(p):
    if len(p) == 0:
        return
    else:
        r = list(p)
        print r.pop(0) + 1
        return rec_increment(r)

print rec_increment([1,2,3,4])

私の質問は、再帰を使用しながらリストのコピーを変更しないことで、コードを簡素化または改善できるかということです。

4

6 に答える 6

5
def rec_increment(p):
    if len(p) == 0:
        return ""                    #If you return an empty string, you don't get the "None" printing at the end.
    else:
        #r = list(p)                 This is not necessary now.
        print p[0]+1                 #r.pop(0) + 1   Rather than pop, just index.
        return rec_increment(p[1:])  # Only recurse on the 2nd-nth part of the list

print rec_increment([1,2,3,4])       # Note that you don't need to both "print" in the function *and* print the result of the function - you can pick which you want to do.
于 2013-10-07T11:20:51.857 に答える