”’
def combination(n,k):
combi=[]
def backtrack(start,comb):
print(comb)
if len(comb)==k:
combi.append(comb.copy())
return
for i in range(start,n+1):
# print(i)
cur=[i]
backtrack(i+1,comb+cur)
comb.pop()
print("comb after",comb)
backtrack(1,[])
return combi
combination(4,3)
”’
I am getting error, IndexError: pop from empty list
When i printed comb to identify error, i am getting this:
1
[]
i is 1
2
[1]
i is 2
3
[1, 2]
i is 3
4
[1, 2, 3]
comb after [1]
i is 4
5
[1, 4]
comb after []
comb after []
i is 3
4
[3]
i is 4
5
[3, 4]
comb after []
Why is my code popping 2 and 3 both when it should only pop 3 after getting [1,2,3].What am i doing wrong?
New contributor
data_geek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.