Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if a string exists in a nested tuple in Python

What is the best (and fastest) way, in Python 2.7.x, to check if a string (or any other data type) exists in a nested tuple?

For example:

RECIPES = (
    ('apple', 'sugar', 'extreme_Force'),
    ('banana', 'syrup', 'magical_ends'),
    ('caramel', 'chocolate', 'pancake_MONSTER'),
    ('banana',('someAnother','banana'))
)

This tuples needs to be checked if banana appears in any of the nested tuple and return the location index, in this case 1,0.

Also, the tuples could be nested to any depth.

like image 667
Nandeep Mali Avatar asked Dec 11 '22 22:12

Nandeep Mali


1 Answers

Recursive multi-location indexing:

import sys
from collections import Sequence,defaultdict

#making code python3-compatible
if sys.version_info[0] == 3:
    basestring = str

def buildLocator(tree):
    locator = defaultdict(list)
    def fillLocator(tree, locator,location):
        for index,item in enumerate(tree):            
            if isinstance(item,basestring):
                locator[item].append(location+(index,))
            elif isinstance(item,Sequence):
                fillLocator(item,locator, location+(index,))
    fillLocator(tree,locator,())
    return locator

RECIPES = (
    ('apple', 'sugar', 'extreme_Force'),
    ('banana', 'syrup', 'magical_ends'),
    ('caramel', 'chocolate', 'pancake_MONSTER'),
    ('banana',('someAnother','banana'))
)
locator = buildLocator(RECIPES)

print(locator['banana'])

prints

[(1, 0), (3, 0), (3, 1, 1)]
like image 184
Odomontois Avatar answered Jan 23 '23 02:01

Odomontois