宿題の質問の場合、各項目を 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])
私の質問は、再帰を使用しながらリストのコピーを変更しないことで、コードを簡素化または改善できるかということです。