0

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.

a_guest
  • 34,165
  • 12
  • 64
  • 118
  • 4
    It looks like Python. It's definitely no C++. Please, prevent TAG SPAMMING which is considered as rude. Also, please, take the [tour] and read [ask]. – Scheff's Cat Jun 11 '21 at 07:09
  • 1
    Adding to @Scheff'sCat's comment, I see no Angular related operations. Please include only related tags. – ruth Jun 11 '21 at 07:11
  • Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – hilberts_drinking_problem Jun 11 '21 at 07:16

2 Answers2

1

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]]
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21
0

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)]
a_guest
  • 34,165
  • 12
  • 64
  • 118