-
Notifications
You must be signed in to change notification settings - Fork 0
/
quiz4-8.py
84 lines (65 loc) · 2.43 KB
/
quiz4-8.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
# -----------------
# User Instructions
#
# Write a function, bsuccessors(state), that takes a state as input
# and returns a dictionary of {state:action} pairs.
#
# A state is a (here, there, t) tuple, where here and there are
# frozensets of people (indicated by their times), and potentially
# the 'light,' t is a number indicating the elapsed time.
#
# An action is a tuple (person1, person2, arrow), where arrow is
# '->' for here to there or '<-' for there to here. When only one
# person crosses, person2 will be the same as person one, so the
# action (2, 2, '->') means that the person with a travel time of
# 2 crossed from here to there alone.
def bsuccessors(state):
"""Return a dict of {state:action} pairs. A state is a (here, there, t) tuple,
where here and there are frozensets of people (indicated by their times) and/or
the 'light', and t is a number indicating the elapsed time. Action is represented
as a tuple (person1, person2, arrow), where arrow is '->' for here to there and
'<-' for there to here."""
here, there, t = state
here = list(here)
there = list(there)
is_torch_here = "light" in here
if is_torch_here:
here.remove("light")
else:
there.remove("light")
if here > there:
from_list = here
target = there
direction = "->"
else:
from_list = there
target = here
direction = "<-"
from_list = list(from_list)
chosen = from_list.pop()
try:
chosen2 = from_list.pop()
except IndexError:
chosen2 = chosen
target.append(chosen)
if chosen2 is not None:
target.append(chosen2)
target.append("light")
target = frozenset(target)
arrow = direction
action = (chosen, chosen2, arrow)
t = t + max([chosen, chosen2])
if direction == "->":
state = (frozenset(from_list), target, t)
else:
state = (target, frozenset(from_list), t)
return {state:action}
def test():
assert bsuccessors((frozenset([1, 'light']), frozenset([]), 3)) == {
(frozenset([]), frozenset([1, 'light']), 4): (1, 1, '->')}
print bsuccessors((frozenset([]), frozenset([2, 'light']), 0))
print { (frozenset([2, 'light']), frozenset([]), 2): (2, 2, '<-')}
assert bsuccessors((frozenset([]), frozenset([2, 'light']), 0)) =={
(frozenset([2, 'light']), frozenset([]), 2): (2, 2, '<-')}
return 'tests pass'
print test()