def cost(H,cond,w=1):
    c={}
    if 'AND' in  cond:
        nodes=cond['AND']
        c['AND' .join(nodes)]=sum(H[n]+w for n in nodes)
    if 'OR' in  cond:
        nodes=cond['OR']
        c['OR' .join(nodes)]=min(H[n]+w for n in nodes)
    return c
def updatecost(H,conds,w=1):
    res={}
    for k in reversed(conds):
        c=cost(H, conds[k], w)
        print(f'{k}: {conds[k]}>>>>>{c}')
        H[k]=min(c.values())

        res[k]=c
    return res
def shortestpath(start,upd,H):
    path=start
    if start in upd:
        vals=list(upd[start].values())
        keys=list(upd[start].keys())
        nxt=keys[vals.index(min(vals))].split()

        if len(nxt) == 1:
            path += '<--' + shortestpath(nxt[0], upd, H)
        else:
            a, b = nxt[0], nxt[-1]
            path += f"<--({keys[0]}) [{shortestpath(a, upd, H)} + {shortestpath(b, upd, H)}]"
    return path

if __name__ == "__main__":
  H = {'A': -1, 'B': 5, 'C': 2, 'D': 4, 'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I': 0, 'J': 0}
  conds = {'A': {'OR': ['B'], 'AND': ['C', 'D']}, 'B': {'OR': ['E', 'F']}, 'C': {'OR': ['G'], 'AND': ['H', 'I']}, 'D': {'OR': ['J']}}
  print('Updated Cost:')
  u = updatecost(H, conds)
  print('*' * 70)
  print('Shortest Path:\n', shortestpath('A', u, H))




