Skip to content

Instantly share code, notes, and snippets.

@89465127
Created March 26, 2013 23:32
Show Gist options
  • Save 89465127/5250265 to your computer and use it in GitHub Desktop.
Save 89465127/5250265 to your computer and use it in GitHub Desktop.
recurses over a mixed data structure of tuples, lists, and dicts, and returns a copy.
# this simple example recurses over a mixed data structure of tuples, lists, and dicts, and returns a copy.
num_recursions = 0
def r(current):
global num_recursions
num_recursions += 1
if isinstance(current, list):
return [r(i) for i in current]
elif isinstance(current, dict):
return {r(k) : r(v) for k, v in current.iteritems()}
elif isinstance(current, tuple):
return tuple([r(i) for i in current])
else:
return current
def main():
structure = {1:[1,2,3], 2:{(1,99):None, 2:[(1,2,3,None)]}}
copy = r(structure)
print structure == copy
structure[2] = None
print structure == copy
print "number of recursions = {}".format(num_recursions)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment