Skip to content

Instantly share code, notes, and snippets.

@n9986
Created September 22, 2012 05:41
Show Gist options
  • Save n9986/3765265 to your computer and use it in GitHub Desktop.
Save n9986/3765265 to your computer and use it in GitHub Desktop.
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'])
# Will print: [(1, 0), (3, 0), (3, 1, 1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment