リストのすべての順列を生成するアルゴリズムを Python で実装しようとしています。しかし、私の for ループでは、元のプレフィックスと残りのリストをそのまま保持したいので、newprefix と newrest を使用してこれらのリストのコピーを作成しようとしていますが、反復ごとに変数の残りを出力すると、変数 rest が変更されています! Pythonでリストの浅いコピーを作成するにはどうすればよいですか? または、試行したロジックに別の問題がありますか?
def perm(prefix, rest):
if len(rest) == 0:
print prefix
for i in range(len(rest)):
#prints in the for loop are just for debugging
print "rest:", rest
print "i=", i
newprefix = prefix
newprefix.append(rest[i])
newrest = rest
newrest.pop(i)
print "old pre : ", prefix
print "newpre=", newprefix
print "newrest=", newrest
perm(newprefix, newrest)
perm([], ['a','b','c'])