I'm studying this book called "A Field Guide to Genetic Programming" for fun. The book uses math structures which to me looks a whole lot like objects in Python. So I'm trying to figure out how to iterate over an object in Python without knowing the names of the keys or child objects in advance.
Here's a photo from the book that I'm attempting to recreate in a python object:
Right now, I'm just trying to get them to print to console. Below is what I have tried.
#!/usr/bin/python
def iterate(object):
for item in object:
print str(object)
iterate(object)
object = {}
object['+'] = []
object['+'].append(5)
object['+'].append(3)
iterate(object)
In the object, I'm just trying to iterate over a very simple math structure:
{"+": [5, 3]}
Which should equate to 5 + 3 eventually, but I haven't figured out how to iterate over the object without knowing it's key names.
Any help is appreciated, thanks.
did not check the code but that might help:
def iterate(object):
if isinstance(object,dict):
for key, item in object.items():
leftItem = item[0]
rightItem = item[1]
if isinstance(leftItem,dict):
return iterate(item)
else:
return str(leftItem) + str(key) + str( iterate(rightItem) )
else:
return object