The code I have written:
l=[i for i in range(1,n+1)]
n=int(input())
k=int(input())
def solve(l,n,r,index,temp,i,ans):
if index==r:
ans.append(temp)
return temp
if i>=n:return
temp[index]=l[i]
solve(l,n,r,index+1,temp,i+1,ans)
solve(l,n,r,index,temp,i+1,ans)
return ans
q=solve(l,n,k,0,[0]*k,0,[])
print(q)
Input:
4
2
Expected output:
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
My output:
[[4,4],[4,4],[4,4],[4,4],[4,4],[4,4]]
In the code if I print the temp during the execution in the solve function it is showing the right combinations but when I return it is showing like this [[4,4],[4,4],[4,4],[4,4],[4,4],[4,4]]
Someone help me with this. I have used the Include and exclude method to generate the combinations.
you need to append temp
's copy, not temp
, or when you change temp
's value, it also change the value in ans
.
code:
def solve(l,n,r,index,temp,i,ans):
if index==r:
ans.append(temp.copy())
return temp
if i>=n:
return
temp[index]=l[i]
solve(l,n,r,index+1,temp,i+1,ans)
solve(l,n,r,index,temp,i+1,ans)
return ans
n=4
k=2
l=[i for i in range(1,n+1)]
q=solve(l,n,k,0,[0]*k,0,[])
print(q)
result:
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
You can use itertools.combinations
:
>>> import itertools as it
>>> list(it.combinations(range(1, 5), r=2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.