0

Hi.
I'm trying to make a function that takes nested tuples and returns a list of each nested tuple. I managed to make a function that returns the values of the tuples (which are strings), but cannot figure out how to retrieve the 'subtuples' in a list.
Here's what I tried so far:

def getNestedList(nestedtuples):
    valuelist = []
    for entry in nestedtuples:
        if type(entry) is str:
            valuelist.extend(entry)
        else:
            valuelist.extend(getNestedList(entry))
    return valuelist

print getNestedList((('1',('2','3')),('4','5')))

Which then returns:

['1', '2', '3', '4', '5']

But my goal is to return something like through recursion:

[['1','2','3'],['2','3'],['4','5'],['1','2','3','4','5']]

I figure this can be done with recursion, but i cannot seem to get a grasp of it. Here is my latest attempt - (I'm rather new to python, so feel free to be amused :) )

def getNestedList(nestedtuples, nestedlist):
    valuelist = []
    for entry in nestedtuples:
        if type(entry) is str:
            valuelist.extend(entry)
            nestedlist.extend(entry)
        else:
            valuelist.extend(getNestedList(entry, nestedlist))
            nestedlist.extend(getNestedList(entry, nestedlist))
    return valuelist, nestedlist
nestedlist = []
getNestedList((('1',('2','3')),('4','5')), nestedlist)
print nestedlist

Any ideas? :)

3
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by jjma
0

I can not see rational rule between wished result and input.

The idea is to make a list of each of the tuples in the nested tuple - e.g.:

(('A','B'),'C'))

should yield

[['A','B'],['A','B','C']]

, as 'A' and 'B' are both part of the same tuple, and 'A', 'B' and 'C' are part of the same tuple.

['A','C']

, should not be returned in the list however, as they don't have a common tuple (other than the one with 'A')

0

Your wish list is very strange however itertool permutation module may help you. Just figure what you are looking for because values entered and results wished are far apart.

;)

0

Thanks. The itertool permutation module solves the problem.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.