-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw4-3.py
116 lines (103 loc) · 4.71 KB
/
hw4-3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# -----------------
# User Instructions
#
# Write a function, subway, that takes lines as input (read more about
# the **lines notation in the instructor comments box below) and returns
# a dictionary of the form {station:{neighbor:line, ...}, ... }
#
# For example, when calling subway(boston), one of the entries in the
# resulting dictionary should be 'foresthills': {'backbay': 'orange'}.
# This means that foresthills only has one neighbor ('backbay') and
# that neighbor is on the orange line. Other stations have more neighbors:
# 'state', for example, has 4 neighbors.
#
# Once you've defined your subway function, you can define a ride and
# longest_ride function. ride(here, there, system) takes as input
# a starting station (here), a destination station (there), and a subway
# system and returns the shortest path.
#
# longest_ride(system) returns the longest possible ride in a given
# subway system.
# -------------
# Grading Notes
#
# The subway() function will not be tested directly, only ride() and
# longest_ride() will be explicitly tested. If your code passes the
# assert statements in test_ride(), it should be marked correct.
import collections
def subway(**lines):
"""Define a subway map. Input is subway(linename='station1 station2...'...).
Convert that and return a dict of the form: {station:{neighbor:line,...},...}"""
subwayMap = collections.defaultdict(dict)
for line, stations in lines.items():
for a,b in neighbours(stations.split()):
subwayMap[a][b] = line
subwayMap[b][a] = line
#print(subwayMap)
return subwayMap
def neighbours(stations):
return [stations[i:i+2] for i in range(len(stations)-1)]
boston = subway(
blue='bowdoin government state aquarium maverick airport suffolk revere wonderland',
orange='oakgrove sullivan haymarket state downtown chinatown tufts backbay foresthills',
green='lechmere science north haymarket government park copley kenmore newton riverside',
red='alewife davis porter harvard central mit charles park downtown south umass mattapan')
def ride(here, there, system=boston):
"Return a path on the subway system from here to there."
result = shortest_path_search(here, lambda s: system[s], lambda s: s == there)
#print here + '->'+ there + ' = ' +str(result)
return result
def longest_ride(system):
""""Return the longest possible 'shortest path'
ride between any two stops in the system."""
stations = system.keys()
longest = ride(stations[0], stations[1], system)
for a in stations:
for b in stations:
next = ride(a, b, system)
if len(next) > len(longest): longest = next
print longest
return longest
def shortest_path_search(start, successors, is_goal):
"""Find the shortest path from start state to a state
such that is_goal(state) is true."""
if is_goal(start):
return [start]
explored = set() # set of states we have visited
frontier = [ [start] ] # ordered list of paths we have blazed
while frontier:
path = frontier.pop(0)
s = path[-1]
for (state, action) in successors(s).items():
if state not in explored:
explored.add(state)
path2 = path + [action, state]
if is_goal(state):
return path2
else:
frontier.append(path2)
return []
def path_states(path):
"Return a list of states in this path."
return path[0::2]
def path_actions(path):
"Return a list of actions in this path."
return path[1::2]
def test_ride():
assert ride('mit', 'government') == [
'mit', 'red', 'charles', 'red', 'park', 'green', 'government']
assert ride('mattapan', 'foresthills') == [
'mattapan', 'red', 'umass', 'red', 'south', 'red', 'downtown',
'orange', 'chinatown', 'orange', 'tufts', 'orange', 'backbay', 'orange', 'foresthills']
assert ride('newton', 'alewife') == [
'newton', 'green', 'kenmore', 'green', 'copley', 'green', 'park', 'red', 'charles', 'red',
'mit', 'red', 'central', 'red', 'harvard', 'red', 'porter', 'red', 'davis', 'red', 'alewife']
assert (path_states(longest_ride(boston)) == [
'wonderland', 'revere', 'suffolk', 'airport', 'maverick', 'aquarium', 'state', 'downtown', 'park',
'charles', 'mit', 'central', 'harvard', 'porter', 'davis', 'alewife'] or
path_states(longest_ride(boston)) == [
'alewife', 'davis', 'porter', 'harvard', 'central', 'mit', 'charles',
'park', 'downtown', 'state', 'aquarium', 'maverick', 'airport', 'suffolk', 'revere', 'wonderland'])
assert len(path_states(longest_ride(boston))) == 16
return 'test_ride passes'
print test_ride()