Search code examples
pythonrecursiontuplesdepth

Python: determining location in nested tuple


I'm wondering if you can help.

I have a tuple that looks like

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

I want to find all numbers and their locations. Forexample, I want all integers except the first in a tuple. I have written a recursive script to do this,

a=[]
def getNumbers(t):
    for i,item in enumerate(t):
        if type(item) is int:
            if i > 0:
                a.append(item)
        else:
            getNumbers(item)

but I cannot seem to determine their depth in the overall tuple. Can you help?


Solution

  • You need to count the depth as you call the recursive function, when you make the initial call pass a depth of zero, then depth + 1 on each recursive call.

    data = (1,2,(3,4,(5,(6,4),2),1,2)) a=[]
    
    def getNumbers(t, depth):
        for i,item in enumerate(t):
            if type(item) is int:
                if i > 0:
                    a.append(item)
            else:
                getNumbers(item, depth + 1)
    
    # call passing initial depth of 0.
    getNumbers(data, 0)