-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path079.Timeit_2.py
More file actions
71 lines (56 loc) · 2.31 KB
/
079.Timeit_2.py
File metadata and controls
71 lines (56 loc) · 2.31 KB
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
import timeit
setup = """\
gc.enable()
locations = {0: "You are sitting in front of a computer learning Python",
1: "You are standing at the end of a road before a small brick building",
2: "You are at the top of a hill",
3: "You are inside a building, a well house for a small stream",
4: "You are in a valley beside a stream",
5: "You are in the forest"}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0}}
"""
locations = {0: "You are sitting in front of a computer learning Python",
1: "You are standing at the end of a road before a small brick building",
2: "You are at the top of a hill",
3: "You are inside a building, a well house for a small stream",
4: "You are in a valley beside a stream",
5: "You are in the forest"}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0}}
def nested_loop():
result = []
for loc in sorted(locations):
exits_to_destination_1 = []
for xit in exits:
if loc in exits[xit].values():
exits_to_destination_1.append((xit, locations[xit]))
result.append(exits_to_destination_1)
return result
def loop_comp():
result = []
for loc in sorted(locations):
exits_to_destination_2 = [(xit, locations[xit]) for xit in exits if loc in exits[xit].values()]
result.append(exits_to_destination_2)
return result
def nested_comp():
exits_to_destination_3 = [[(xit, locations[xit]) for xit in exits if loc in exits[xit].values()]
for loc in sorted(locations)]
return exits_to_destination_3
print(nested_loop())
print(loop_comp())
print(nested_comp())
result_1 = timeit.timeit(nested_loop, setup, number=10000)
result_2 = timeit.timeit(loop_comp, setup, number=10000)
result_3 = timeit.timeit(nested_comp, setup, number=10000)
print("Nested Loop:\t{}".format(result_1))
print("Loop Comp:\t{}".format(result_2))
print("Nested Comp:\t{}".format(result_3))