Creating objects and their reference from text input without losing informations

Basically what i’m trying to do is to implement a dependency resolving algorithm.

Suppose I have a list like the following:

package1:
package2: package1
package3: package1, package2
package4: package1 
package5: package1, package2 

Basically, package1 depends just on itself, package2 depends on package1, package3 depends on 1 and 2 and so on.

What I did until now is the following:

  • First, I open the file containing the list
  • Second a read each word of the file, putting it on a list
  • Third, i enter inside the list, if the elements ends with : I create an object with his name(meaning its a package)

Suppose i run the program with the list above, the output is like this:

<__main__.Node object at 0x100740ac8>
<__main__.Node object at 0x100740b00>
None
<__main__.Node object at 0x100740ac8>
None
None
<__main__.Node object at 0x100740b00>
None
<__main__.Node object at 0x100740ac8>
None
None

The part where i create new packages object works fine, since as we can see there are objects, but the part where i reference the dependency with the main package fails, since it displays None, which is not correct.

In order to be correct, the output should be like the following

package1
package2
package1
package3
package1
package2
package4
package1
package5
package1
package2

I think that were i’m making mistakes is this part:

f = open('data.txt','r')


text = []
resolved = []
unresolved = []

for line in f.readlines():
    for char in line.split():
        text.append(char)



class Node:

    def __init__(self, name):
        self.name = name
        self.edges = []

    def addEdge(self, node):
        self.edges.append(node)

    def dep_resolve(self, resolved, unresolved):
        unresolved.append(self)
        print (self.name)
        for edge in self.edges:
            if edge not in resolved:
                if edge in unresolved:
                    raise Exception('Circular')
                edge.dep_resolve(resolved, unresolved)
        resolved.append(self)
        unresolved.remove(self)

global flag
for i in range(len(text)):
    if text[i].endswith(':'):
        newstr = text[i].replace(':', '')
        newstr = Node(newstr)
        flag = newstr
        print(flag.name)

    else:
        flag.addEdge(text[i])
        print(flag.addEdge(text[i]))

and in particular the else where i reference to an object of type str while i should reference to an object of type Node but i have no idea how to fix it.

If you need more of the code i will put it


Source: oop

Leave a Reply