I am trying to generate all possible 3 combinations from the set {1,2,3,4,5} using recursion.
Expected output: [[1,2,3],[1,2,4],[1,2,5],[2,3,4],[2,3,5],[3,4,5],[1,3,4],[1,3,5],[1,4,5],[2,4,5]]
The logic that I am using is that any 3-set combination will either have the first element in it or not have. I am also using the concatenation of lists. Example:
[[1,2,3]] + [[a,b]] gives [[1,2,3],[a,b]]
The below code that uses the above logic doesn't seem to work. I am self-learning so, if I make a mistake, please be patient with me. I am aware there are errors in my recursion. But, trying to backtrack the output in recursion problems is proving quite difficult for me. Could you please let me know where could be the flaw in this program and guide me towards suitable resources where such types of questions can be better handled. What is the right way of thinking in such questions? Thanks a lot for helping.
Code:
sol = [1,2,3,4,5]
b=3
y= []
def combinations(sol, b):
global y
if len(sol) == b or len(sol)==1 :
return [sol]
y.append([[sol[0]] + combinations(sol[1:], b-1)] + combinations(sol[1:],b))
return y
print(combinations(sol,b)