0

First question for this Problem is: How can I call a function with a tuple of tuples, my programm should be able to handle any number of tuples.

Second question: I found a way, but with defined tuples in my code and it works, so I need a hint how to call the function with a tuple with any number of tuples in it.

My code so far:

def merge(tuples):
    tuples = ((2, 3, 4), (1, 6), (5, 1, 7))
    largest_tuple = len(tuples[0])
    for i in tuples:
        largest_tuple = max(largest_tuple, len(i))
    new_tuples = []
    for i in range(largest_tuple):
        tup = []
        for j in tuples:
            if i < len(j):
            tup.append(j[i])
    tup.sort()
    new_tuples = new_tuples+tup
    new_tuple = tuple(new_tuples)
    print(new_tuple)

For example:

merge((2, 3, 4), (1, 6), (5, 1, 7))

return:

(1, 2, 5, 1, 3, 6, 4, 7)

1 Answers1

0

Use A Recursive Function:

merged_tuple = [] # Here is where the solution goes

    def merge(tuple_set):
        for value in tuple_set: # Looping over the current tuple
            if type(value) == tuple: # if that value is a tuple
                merge(value) # Perform the function all over again
            else:
                merged_tuple.append(value) # Add the number to the solution set
                
        return tuple(sorted(merged_tuple))
tominekan
  • 303
  • 2
  • 10
  • This code don't work unfortunately, I got a RecursionError. And like I said in the comments in the post above this one: The values need to get ordered by size in positional order (top to bottom) ` tuples = ((2, 3 ,4),(1, 6),(5, 1, 7)) returns-> combined_tuple = (1, 2, 5, 1, 3, 6, 4, 7) ` – John Hopesand Aug 27 '20 at 07:26
  • `[Previous line repeated 995 more times] File "merge_tuple.py", line 5, in merge if type(value) == tuple: # if that value is a tuple RecursionError: maximum recursion depth exceeded while calling a Python object` – John Hopesand Aug 27 '20 at 08:12
  • Could you please explain what you mean, when you want to solve a tuple, do you want it to solve anything from `(5, (3, 2 (4, 1))) ` to `((4, 3,) 5, 2, 1).` or do you just want the code to solve a tuple with only tuples inside of it like `((1, 4, 3), (2,5))` – tominekan Aug 27 '20 at 15:23
  • Only a tuple with any number of tuples in it. – John Hopesand Aug 28 '20 at 07:02
  • That code should work then, what type of computer do you have? – tominekan Aug 28 '20 at 16:00