0

I have a list of orders:

id, dependency_id
1,  2
1,  3
3,  4
5,  2
3,  6

I have to output something like this:

Id: 1, Name: Order 1
Dependencies
   Id: 2, Name: Order 2
   Id: 3, Name: Order 3
   Dependencies
      Id: 4, Name: Order 4
      Id: 6, Name: Order 6
Id: 5, Name: Order 5
Dependencies
   Id: 2, Name: Order 2

What sort of recursive algorithm should I use? I am stuck

This is what I have so far:

dependencies = {}
def read():
  f = open("dependencies.txt", "r")
  # contents = f.read() #reads the whole file
  #print(contents) #prints everything
  #print(contents[0]) #prints first letter
  lines = f.readlines()
  for i in range(1, len(lines)):
    dep = lines[i].split(",")
    dep[1] = dep[1].rstrip()
    try:
      depList = dependencies.get(dep[0], [])
      depList.append(dep[1])
      dependencies[dep[0]] = depList
    except:
      dependencies[dep[0]] = [dep[1]]
if __name__ == "__main__":
  read()

This returns: {'1': ['2', '3'], '3': ['4', '6'], '5': ['2']}

jdehesa
  • 58,456
  • 7
  • 77
  • 121
Coder
  • 151
  • 2
  • 12
  • My answer https://stackoverflow.com/a/27277605/56778 shows how to do this in C#. You could use the same technique in Python. – Jim Mischel Jun 28 '19 at 16:39
  • Is the order supposed to represent the traversal order or is it just a copy of the value? – Mark Jun 28 '19 at 16:41
  • You need to have an adjacency list created first for each node and also calculate the in-degree of each node. Then just implement DFS where you only print the nodes after you are done with complete DFS. Store them in Stack till then and after DFS is over, print the stack elements. – CodeHunter Jun 28 '19 at 18:09

1 Answers1

0

You could do something like this;

#-*- coding:utf-8 -*-

table = [(1, 2), (1, 3), (3, 4), (5, 2), (3, 6)]

deps = {}
for k, d in table:
    if k not in deps:
        deps[k] = {}
    if d not in deps:
        deps[d] = {}

    deps[k][d] = True
    deps[d][k] = True

def p(a, d, stack):
    print "%sId: %d, Name: Order %d" % (d * "  ", a, a)
    stack.append(a)
    for b, v in deps[a].iteritems():
        if not b in stack:
            print (d*"  ") + " Dependencies"
            p(b, d+1, stack)

for k, d in table:
    p(k, 0, [])
Rafael Quintela
  • 1,908
  • 2
  • 12
  • 14
  • this almost gets the job done. you do not need deps[d][k] = True but prints duplicates for each item in the table list. Any idea how to fix that? – Coder Jun 28 '19 at 19:34
  • I am working on this problem and I have hit a wall. I think I approached it the wrong way. I had originally converted orders.txt and dependencies.txt to DataFrames. And was hoping there would be a way to enforce dependencies this way, but this is incorrect. - I am confused as to how I can apply the dependencies outlined in the dependencies.txt file to the orders.txt file. – Paul Russell Oct 24 '20 at 19:24