Python Forum
how can I initialize this code ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how can I initialize this code ?
#1
Hey there !

Im having trouble with this code:
class Graph:
    def __init__(self):
        self.graph = {
           'A': {'B': 10, 'D': 4, 'F': 10},
           'B': {'E': 5, 'J': 10, 'I': 17},
           'C': {'A': 4, 'D': 10, 'E': 16},
           'D': {'F': 12, 'G': 21},
           'E': {'G': 4},
           'F': {'H': 3},
           'G': {'J': 3},
           'H': {'G': 3, 'J':5},
           'I': {},
           'J': {'I': 8}
        }
 
    def shortpath(self, start, end):
        D = {} # final distances dict
        P = {} # Predecessor dict
        #Fill the dicts with default values
        for node in self.graph.keys():
            D[node] = - 1 # Vertices are unreachable
            P[node] = "" # Vertices have no predecessors
             
        D[start] = 0 # The start vertex needs no move
         
        # print(f'D: {D}\nP: {P}')
        unseen_nodes = list(self.graph.keys()) # All nodes are unseen
         
        while len(unseen_nodes) > 0:
            # print(f'unseen_nodes: {unseen_nodes}')
            # Select the node with the lowest value in D (final distance)
            shortest = None
            node = ''
            for temp_node in unseen_nodes:
                if shortest == None:
                    shortest = D[temp_node]
                    node = temp_node
                elif D[temp_node] < shortest:
                    shortest = D[temp_node]
                    node = temp_node
                    #remove the selected node from unseen_nodes
     
                if node in unseen_nodes:
                    unseen_nodes.remove(node)
  
        #for each child (connected vertex) of the current node
        for child_node, child_value in self.graph[node].items():
            if D[child_node] < D[node] + child_value:
                D[child_node] = D[node] + child_value
                #To go to child_node, you have to go through node
                P[child_node] = node
                #Set a clean path
                path = []
                # we begin from the end 
                node = end
 
        #while we are not arrived at the beginning
        while not (node == start):
            if path.count(node) == 0:
                path.insert(0, node) #Insert the predecessor of the current node
                node = P[node] # The current node becomes its predecessor
            else:
                break
                path.insert(0, start)#Finally, insert the start vertex
            return path
 
    def main():
        gg = Graph()
        gg.shortpath('C', 'I')
 
    if __name__ == '__main__':
        main()
I previously got help from a very kind soul in this forum, who suggest I should remove line 71 and remove the indentation from line 72 and after that, I should run:
python programname.py
It was to no avail, since I get SyntaxError when I run the aforementioned command in a different cell....
I just want to run it and get the solution...


Many thanks in advance !
Reply
#2
all of these lines needs to be dedented 4 spaces to the left

to this
def main():
    gg = Graph()
    gg.shortpath('C', 'I')

if __name__ == '__main__':
    main()
Recommended Tutorials:
Reply
#3
Hey,

thanks for your reply !

How can I run it afterwards ? I mean, how can I get the results ?
I indented the lines 4 spaces to the right.
Just tried giving the command
shortpatch(graph, 'C', 'I')
Instead of getting the path, I got an error since "shorpath" hasnt been given a value!
Reply
#4
(Jan-22-2019, 01:54 PM)grandpapa10 Wrote: I indented the lines 4 spaces to the right.
I said dedent to the left, not indent to the right. It has to be all the way to the left.

(Jan-22-2019, 01:54 PM)grandpapa10 Wrote: I got an error since "shorpath" hasnt been given a value!
it has been given a value, but it takes 2 parameters start and end
Quote:
def shortpath(self, start, end):

Currently the code does not show anything so you need to print it to see the results.
def main():
    gg = Graph()
    path = gg.shortpath('C', 'I')
    print(path)

if __name__ == '__main__':
    main()
Output:
$ python3 test6.py ['I']
Recommended Tutorials:
Reply
#5
Hey metulburr,
I did what you suggested and got the same result…
Even if it's a start and it minders my frustration with this code, I still would like to know why the output doesnt
display the whole short path from C to I ..

I m eager for your reply !
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  2 ways to initialize a list with all zero quazirfan 2 1,745 Aug-06-2021, 03:27 PM
Last Post: deanhystad
  Fatal Python error: init_sys_streams: can't initialize sys standard streams Attribute FatalPythonError 24 57,334 Aug-22-2018, 06:10 PM
Last Post: FatalPythonError

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020