0

There are better ways of finding a min in a tree but my main question is why I am unable to change record and keep track of it throughout the trace. I would prefer not to use global variables.

record = sys.maxsize
def findMin(tree, record):
        if list(tree.keys())[0] < record:
                record = list(tree.keys())[0]
        if len(tree[list(tree.keys())[0]]) == 0:
                return
        else:
                for v in tree[list(tree.keys())[0]]:
                        findMin(v, record)
findMin({100: [{40: [{34: [{15: []}]}], 56: [{67: [{13: [{9:[]}]}]}], 79: [{92: [{84:[{6:[]}]}]}]}]}
, record)
print(record)
zetologos
  • 163
  • 2
  • 4
  • 14

1 Answers1

0

Avoiding globals is tricky in this kind of problem. Here's one approach using python's versatile generators -

def find_min (tree):
  # recursively list all keys and values
  def values (t):
    if (isinstance(t, dict)):
      for (k,v) in t.items():
        yield k
        yield from values(v)
    elif (isinstance(t, list)):
      for v in t:
        yield from values(v)
    else:
      yield t
  # find lowest value in iterable
  def min (iter):
    a = inf
    for x in iter:
      if x < a:
        a = x
    return a
  # find lowest value in tree
  return min(values(tree))

Testing it on our tree of data -

t = {100: [{40: [{34: [{15: []}]}], 56: [{67: [{13: [{9:[]}]}]}], 79: [{92: [{84:[{6:[]}]}]}]}]}

print(find_min(t))
# 6
Mulan
  • 129,518
  • 31
  • 228
  • 259