0

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:

Math Objects

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.

Wayne Workman
  • 131
  • 1
  • 5
  • 1
    Possible duplicate of [Loop through all nested dictionary values?](https://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values) – quamrana Dec 03 '17 at 18:45

2 Answers2

2

What you are attempting to create is a binary tree, i.e a structure that contains a node and two children. For the dictionary you have created, you can iterate using a for-loop and dict.items():

d = {"+": [5, 3]}
for parent, children in d.items():
    print(parent, children)

However, for a more generic, recursive solution:

d = {"+": [5, 3]}
def flatten(s):
   for i in s:
      if isinstance(i, int) or isinstance(i, str):
         print(i)
      else:
         flatten(i)

flatten(d.items())

Output:

'+'
 5
 3
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

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