[英]Returned list is different from what it is inside function
Here is my code:这是我的代码:
def solve(lists,sums,num_list_,num,a):
if len(num_list_)==num:
if add(lists,num_list_)==sums:
print(num_list_)
return a+[num_list_]
return a
num_list=copy.deepcopy(num_list_)
for x in range(10):
num_list[num]=x
a=solve(lists,sums,num_list,num+1,a)
return a
def add(lists,unkown_num_list):
answer=0
for x in lists:
st=''
for y in x:
if isinstance(y,int):
y=str(unkown_num_list[y])
st+=y
st=int(st)
answer+=st
return answer
unkown_num_list=[]
difference=[]
a=solve([[0], [1, 0], [2, 1, 0], [3, 2, 1, 0]],2000,[0, 0, 0, 0],0,[])
It printed:它打印:
[0, 0, 0, 2]
[0, 0, 5, 1]
[5, 6, 4, 1]
[5, 6, 9, 0]
But for variable a
, it is this:但是对于变量a
,它是这样的:
[[0, 0, 0, 9], [0, 0, 5, 9], [5, 6, 4, 9], [5, 6, 9, 9]]
Why are these two different?为什么这两个不同?
Is it because I used recursion?是因为我使用了递归吗? But other times, they don't have this kind of error.但其他时候,他们没有这种错误。
I am using python3.6.1 and macOS High Sierra.我正在使用 python3.6.1 和 macOS High Sierra。
I am a beginner in Python, please point out any incorrect code.我是 Python 的初学者,请指出任何不正确的代码。
Although you have a deepcopy in your solve
function, in the for
loop you still mutate the same num_list
list after having added it to the result.尽管您的solve
function 中有一个 deepcopy,但在for
循环中,您仍然会在将相同的num_list
列表添加到结果后对其进行变异。 So in cases where the for
loop has more than one iteration, you'll get unexpected results.所以在for
循环不止一次迭代的情况下,你会得到意想不到的结果。
One solution is to move the deepcopy inside the for
loop:一种解决方案是在for
循环内移动 deepcopy:
def solve(lists,sums,num_list_,num,a):
if len(num_list_)==num:
if add(lists,num_list_)==sums:
print(num_list_)
return a+[num_list_]
return a
for x in range(10):
num_list=copy.deepcopy(num_list_) # <----------
num_list[num]=x
a=solve(lists,sums,num_list,num+1,a)
return a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.