Created
March 26, 2013 23:32
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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