def a_function(n, a, b, c):
if n == 1:
print((a,b))
else:
a_function(n-1, a, c, b)
print((a,b))
a_function(n-1, c, b, a)
a_function(3, 1, 2, 3)
How to make the function to return a tuple instead of output above?
(something like:((1, 2), (1, 3), (2, 3), (1, 2), (3, 1), (3, 2), (1, 2)) )
You can return a tuple of tuple, and keep concatenating them as you return from the recursive calls . Example -
def a_function(n, a, b, c):
if n == 1:
return ((a,b),)
else:
x = a_function(n-1, a, c, b)
return x + ((a,b),) + a_function(n-1, c, b, a)
Demo -
>>> def a_function(n, a, b, c):
... if n == 1:
... return ((a,b),)
... else:
... x = a_function(n-1, a, c, b)
... return x + ((a,b),) + a_function(n-1, c, b, a)
...
...
>>> a_function(3, 1, 2, 3)
((1, 2), (1, 3), (2, 3), (1, 2), (3, 1), (3, 2), (1, 2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With