私は再帰を学習していますが、なぜこれが機能しないのか分かりません。それは何をすべきPython - 再帰:intを複写する、リスト内のintを複製する、ネストされたリスト内にintを複写する
:
>>> copy(1)
[1, 1]
>>> copy([1, 2])
[1, 1, 2, 2]
>>> copy([1, [2, 3]])
[1, 1, [2, 2, 3, 3]]
だから、基本的にはコードだけで各整数を複製する必要があります。注:リスト内の位置とフォーマット(ネストされたリストの場合)は変更されません。このコードはすべて、リスト内の各intの横に重複するintを挿入します。
コード:
def copy(nested_list):
new_list = []
#if list is empty
if isinstance(nested_list, list) and len(nested_list) == 0:
return new_list
# if it's only an int
elif isinstance(nested_list, int):
new_list.append(nested_list)
new_list.append(nested_list)
else:
# if list is a list
if isinstance(nested_list, list):
for num in range(len(nested_list)):
if isinstance(nested_list[num], int):
new_list.append(nested_list[num])
new_list.append(nested_list[num])
elif isinstance(nested_list[num], list):
copy(nested_list[num])
else:
pass
return new_list
それは最後の1を除いて、例のほとんどのために動作します。あなたのcopy
関数は再帰的ですが、あなたは完全にcopy
に再帰呼び出しの結果を無視
Expected:
[1, 1, [2, 2, 3, 3]]
Got:
[1, 1]
ahhはい、私は再帰呼び出しの結果を処理する必要があります。良いキャッチ、ありがとう! – Theo
OPの間違いとあなたのコードがなぜ機能するのか、あなたの答えに言及してください。 –
@ rakeb.mazharul私はこれを私の心に残していきます。私はあなたの提案に感謝します。 –