-1

I'm given a nested structure of tuples with 2 elements each, and want to convert it to a flat structure

I've tried using * to loop through and flatten, but am stuck since each tuple is nested in another one

Example input: (((((1, 2), 3), 4), 5), 6)

Example output: (1, 2, 3, 4, 5, 6)

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • 4
    "I've tried using * to loop through and flatten..." what does this mean? Can you show us your code so that we have some context? Ideally, we'd be able to help you through your own solution instead of giving you an answer from scratch. – Jordan Singer Apr 03 '19 at 13:27
  • Please add the code you've tried. Ideally with some information about the parts of the code you are struggling to understand. – OrderAndChaos Apr 03 '19 at 13:29
  • Are the tuple always like in the example e.g. tuple as first element and a single element after it ? – Dimitar Apr 03 '19 at 13:35
  • I didn't see the the tuple had only two values. Removed my incorrect answer – Slayer Apr 03 '19 at 13:43

3 Answers3

2

Using recursion

def convert(data):
    result = []
    for item in data:
        if isinstance(item, tuple):
            result.extend(convert(item))
        else:
            result.append(item)
    return tuple(result)

data = (((((1, 2), 3), 4), 5), 6)
print(convert(data))
furas
  • 134,197
  • 12
  • 106
  • 148
1

You can use recursion with a generator for a shorter, cleaner solution:

def flatten(d):
  for i in d:
     yield from [i] if not isinstance(i, tuple) else flatten(i)

print(tuple(flatten((((((1, 2), 3), 4), 5), 6))))

Output:

(1, 2, 3, 4, 5, 6)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

Being witty:

def flatten(T):
    if T == ():
       return T
    if isinstance(T[0], tuple):
       return flatten(T[0]) + flatten(T[1:])
    return T[:1] + flatten(T[1:])


s = (((((1, 2), 3), 4), 5), 6)
print("Flattened tuple: ", flatten(s))    

OUTPUT:

Flattened tuple:  (1, 2, 3, 4, 5, 6)
DirtyBit
  • 16,613
  • 4
  • 34
  • 55