[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

constructed strings to do the work of seven assignment statements (A=Graph('A'),
B=Graph('B'), and so on).


Example 18-20. PP4E\Dstruct\Classics\gtestobj1.py


"build class-based graph and run test searches"


from graph import Graph


this doesn't work inside def in 3.1: B undefined


for name in "ABCDEFG": # make objects first
exec("%s = Graph('%s')" % (name, name)) # label=variable-name


A.arcs = [B, E, G]
B.arcs = [C] # now configure their links:
C.arcs = [D, E] # embedded class-instance list
D.arcs = [F]
E.arcs = [C, F, G]
G.arcs = [A]


A.search(G)
for (start, stop) in [(E,D), (A,G), (G,F), (B,A), (D,A)]:
print(start.search(stop))


Running this test executes the same sort of graph walking, but this time it’s routed
through object methods:


C:\...\PP4E\Dstruct\Classics> python gtestobj1.py
[[E, C, D], [E, G, A, B, C, D]]
[[A, G], [A, E, G], [A, B, C, E, G]]
[[G, A, E, F], [G, A, B, C, D, F], [G, A, B, C, E, F], [G, A, E, C, D, F]]
[[B, C, E, G, A]]
[]

The results are the same as for the functions, but node name labels are not quoted:
nodes on path lists here are Graph instances, and this class’s repr scheme suppresses
quotes. Example 18-21 is one last graph test before we move on; sketch the nodes and
arcs on paper if you have more trouble following the paths than Python.


Example 18-21. PP4E\Dstruct\Classics\gtestobj2.py


from graph import Graph


S = Graph('s')
P = Graph('p') # a graph of spam
A = Graph('a') # make node objects
M = Graph('m')


S.arcs = [P, M] # S leads to P and M
P.arcs = [S, M, A] # arcs: embedded objects
A.arcs = [M]
print(S.search(M)) # find all paths from S to M


1394 | Chapter 18: Data Structures

Free download pdf