Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing outputs into tuple [python]

Tags:

python

tuples

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)) )

like image 687
mshx Avatar asked May 13 '26 03:05

mshx


1 Answers

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))
like image 175
Anand S Kumar Avatar answered May 15 '26 16:05

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!