Python Graphlib module static_order( )-2














































Python Graphlib module static_order( )-2



In the previous article, we have seen some information about static_order( )

In this article, we shall see more about static_order( ) method 

*The order of elements returned by static_order( ) depends on how u   inserted the elements  in the graph.
Example:
Topologicalorder-1:

from graphlib import TopologicalSorter
  
ts = TopologicalSorter()
  
ts.add(3, 2, 1)
ts.add(1, 0)
  
print("TopologicalOrder1=",end=" ")
print([*ts.static_order()])

 Output:
TopologicalOrder1= [2, 0, 1, 3]

Topologicalorder-2:

from graphlib import TopologicalSorter
ts2 = TopologicalSorter()

ts2.add(1, 0)

ts2.add(3, 2, 1)

print("TopologicalOrder2=",end=" ")

print([*ts2.static_order()])

Output:
TopologicalOrder2= [0, 2, 1, 3]

By observing TopologicalOrder1 and TopologicalOrder2, we conclude 
 that order of elements depends upon order of insertion.


*If any cycles is detected in the graph, CycleError will be raised.
For Example:
from graphlib import TopologicalSorter
tos = TopologicalSorter()

tos.add(1, 0)

tos.add(3, 2, 1)
tos.add(0, 1)


print([*tos.static_order()])

Output:
Traceback (most recent call last):
  File "C:\Users\findm\AppData\Local\Programs\Python\Python39\graphlib1.py", line 15, in <module>
    print([*tos.static_order()])
  File "C:\Users\findm\AppData\Local\Programs\Python\Python39\lib\graphlib.py", line 242, in static_order
    self.prepare()
  File "C:\Users\findm\AppData\Local\Programs\Python\Python39\lib\graphlib.py", line 104, in prepare
    raise CycleError(f"nodes are in a cycle", cycle)
graphlib.CycleError: ('nodes are in a cycle', [1, 0, 1])




Comments