Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Flatten Nested Tuples

Python – Flatten Nested Tuples

Sometimes, while working with Python Tuples, we can have a problem in which we need to perform flattening of tuples, which can be nested and undesired. This can have application across many domains such as Data Science and web development. Let’s discuss certain way in which this task can be performed.

Input : test_tuple = ((4, 7), ((4, 5), ((6, 7), (7, 6))))
Output : ((4, 7), (4, 5), (6, 7), (7, 6))

Input : test_tuple = ((4, 7), (5, 7), (1, 3))
Output : ((4, 7), (5, 7), (1, 3))

Method 1: Using recursion + isinstance() The combination of above functionalities can help us achieve solution to this problem. In this we use recursion to perform the task of digging into each tuple for inner tuples, and for decision of flattening, isinstance() is used depending upon tuple container or primitive data. 

Step-by-step approach :

  1. Define a function flatten that takes a nested tuple as input.
  2. If the input tuple is a tuple of length 2 and the first element is not a tuple, wrap it in a tuple and return it.
  3. If the input tuple is not a tuple of length 2, or if the first element is a tuple, continue to the next step.
  4. Create an empty list res to store the flattened tuple.
  5. Iterate over each element sub in the input tuple.
  6. If sub is a tuple, recursively call flatten on sub and add the flattened tuple to res.
  7. If sub is not a tuple, add it to res.
  8. Convert res to a tuple and return it.
  9. Initialize a nested tuple test_tuple.
  10. Print the original tuple to the console.
  11. Call flatten on test_tuple and store the result in res.
  12. Print the flattened tuple to the console.

Python3




# Python3 code to demonstrate working of
# Flatten Nested Tuples
# Using recursion + isinstance()
 
# helper function
def flatten(test_tuple):
     
    if isinstance(test_tuple, tuple) and len(test_tuple) == 2 and not isinstance(test_tuple[0], tuple):
        res = [test_tuple]
        return tuple(res)
 
    res = []
    for sub in test_tuple:
        res += flatten(sub)
    return tuple(res)
 
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten Nested Tuples
# Using recursion + isinstance()
res = flatten(test_tuple)
 
# printing result
print("The flattened tuple : " + str(res))


Output : 

The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : ((4, 5), (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))

Time complexity: The time complexity of the function is O(N), where N is the total number of elements in the input nested tuple.
Auxiliary space: The auxiliary space used by the function is also O(N), where N is the total number of elements in the input nested tuple

Method 2: itertools.chain.from_iterable() 

 This program uses itertools.chain.from_iterable() method to flatten the nested tuple test_tuple and returns a new flattened tuple.

Python3




import itertools
 
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten Nested Tuples using itertools.chain.from_iterable()
res = tuple(itertools.chain.from_iterable(test_tuple))
 
# printing result
print("The flattened tuple : " + str(res))


Output

The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 5, (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))

Time complexity: O(n), where n is the total number of elements in the nested tuple.
Space complexity: O(n), since the output tuple contains n elements.

Method 3:  use a generator function that iterates over the elements of the input tuple and yields non-tuple values, and recursively calls itself on tuple values. 

Here’s how the flatten_tuples function works:

  1. It iterates over the elements of the input tuple t.
  2. If the current element x is a tuple, it recursively calls flatten_tuples on x using the yield from statement.
  3. If the current element x is not a tuple, it yields it to the calling function.

Python3




def flatten_tuples(t):
    for x in t:
        if isinstance(x, tuple):
            yield from flatten_tuples(x)
        else:
            yield x
 
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# Flatten Nested Tuples
# Using generator function
res = tuple(flatten_tuples(test_tuple))
 
# printing result
print("The flattened tuple : " + str(res))


Output

The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 5, 4, 7, 8, 9, 10, 11, 9, 10, 3, 4)

This approach has a time complexity of O(n), where n is the total number of elements in the input tuple, since each element is visited once.
The auxiliary space is O(d), where d is the depth of the nested tuples, since the recursion depth is bounded by the depth of the nested tuples.

Method 4: using the reduce() function from the functools module

  1. The flatten_tuple() function takes a nested tuple as input and returns a flattened tuple.
  2. The reducer() function is a helper function that is used in the reduce() function. It takes two arguments: an accumulator (acc) and a value (val). If the value is a tuple, it recursively calls flatten_tuple() on the tuple and concatenates the result to the accumulator. If the value is not a tuple, it appends the value to the accumulator.
  3. The reduce() function applies the reducer() function to each element of the nested tuple and reduces it to a single flattened tuple.
  4. Finally, the flattened tuple is returned as the result.

Python3




from functools import reduce
 
def flatten_tuple(nested_tuple):
    def reducer(acc, val):
        if isinstance(val, tuple):
            return acc + flatten_tuple(val)
        else:
            return acc + (val,)
 
    return reduce(reducer, nested_tuple, ())
 
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# flatten nested tuples using reduce() function
res = flatten_tuple(test_tuple)
 
# printing result
print("The flattened tuple : " + str(res))


Output

The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 5, 4, 7, 8, 9, 10, 11, 9, 10, 3, 4)

Time Complexity: O(n), where n is the total number of elements in the nested tuple, as each element is visited exactly once.
Auxiliary Space: O(n), as the maximum depth of recursion is equal to the maximum nesting level of the tuple.

Method 5: Using a stack

  • Create an empty stack and push the given tuple onto it.
  • Create an empty list to store the flattened values.
  • While the stack is not empty:
    a. Pop the top element from the stack.
    b. If the popped element is a tuple, push its elements onto the stack.
    c. If the popped element is not a tuple, append it to the flattened list.
  • Return the flattened list.

Python3




def flatten_tuple(nested_tuple):
    stack = [nested_tuple]
    flattened_list = []
     
    while stack:
        top = stack.pop()
        if isinstance(top, tuple):
            stack.extend(top)
        else:
            flattened_list.append(top)
     
    return tuple(flattened_list)
 
 
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
 
# printing original tuple
print("The original tuple : " + str(test_tuple))
 
# flatten nested tuples using stack
res = flatten_tuple(test_tuple)
 
# printing result
print("The flattened tuple : " + str(res))


Output

The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : (4, 3, 10, 9, 11, 10, 9, 8, 7, 4, 5, 4)

Time complexity: O(n) – where n is the total number of elements in the nested tuple.
Auxiliary space: O(n) – where n is the total number of elements in the nested tuple.

RELATED ARTICLES

Most Popular

Recent Comments