Maze en Python (maze.py )
1 #!/bin/env python
2 # Python solution to mamund's maze problem (functional style)
3 # see http://amundsen.com/examples/misc/maze-client.html
4
5 from xml. etree. ElementTree import XML
6 from httplib2 import Http
7
8 MAZE = "http://amundsen.com/examples/mazes/2d/five-by-five/"
9 RULES = {
10 'east' : [ 'south' , 'east' , 'north' , 'west' ],
11 'south' : [ 'west' , 'south' , 'east' , 'north' ],
12 'west' : [ 'north' , 'west' , 'south' , 'east' ],
13 'north' : [ 'east' , 'north' , 'west' , 'south' ]
14 }
15
16 def get ( uri):
17 """ return the XML from the given uri """
18 resp, content = Http (). request (
19 uri,
20 headers={
21 'Accept' :
22 "application/vnd.amundsen.maze+xml" })
23 return XML ( content)
24
25 def get_links ( uri):
26 """
27 return a dict {rel: href} of the <link>s found at the given uri
28 """
29 return dict (
30 ( link. get ( 'rel' ), link. get ( 'href' ))
31 for link in get ( uri). findall ( '*/link' )
32 )
33
34 def selector ( rules):
35 """
36 a little closure to create the next-link selector based on the
37 given rules
38 """
39 def select ( facing, links):
40 """
41 app logic:
42 given the current facing direction and the available links,
43 chooses the next direction (according to the rules),
44 follows the link and return the new facing direction and the
45 available links for the current state
46 """
47 if facing is None and 'start' in links:
48 return ( 'north' , get_links ( links[ 'start' ]))
49 if 'exit' in links:
50 return ( 'exit' , get_links ( links[ 'exit' ]))
51 for choice in rules[ facing]:
52 if choice in links:
53 return ( choice, get_links ( links[ choice]))
54 return select
55
56 def find_path ( maze, rules):
57 """
58 just follow the links until exit, yielding the current state
59 """
60 select_next = selector ( rules)
61 facing, links = None , get_links ( maze)
62 while facing is not 'exit' :
63 facing, links = select_next ( facing, links)
64 yield ( facing, links)
65
66 if __name__ == '__main__' :
67 import sys
68 if len ( sys. argv) == 2 :
69 maze = sys. argv[ 1 ]
70 else :
71 maze = MAZE
72 for step, ( facing, links) in enumerate ( find_path ( maze, RULES)):
73 print " %s : go to %s " % ( step, facing)
74 print " < %s >" % ( links. get ( 'current' , '' ),)
75 print "I'm free !"
76