Skip to content

Commit 9d92e56

Browse files
committed
comprehensions koniec
1 parent 89589c8 commit 9d92e56

File tree

9 files changed

+413
-0
lines changed

9 files changed

+413
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Create a comprehension that returns a list of all the locations that have an exit to the forest.
2+
# The list should contain the description of each location, if it's possible to get to the forest from there.
3+
#
4+
# The forest is location 5 in the locations dictionary
5+
# The exits for each location are represented by the exits dictionary.
6+
#
7+
# Remember that a dictionary has a .values() method, to return a list of the values.
8+
#
9+
# The forest can be reached from the road, and the hill; so those should be the descriptions that appear in your list.
10+
#
11+
# Test your program with different destinations (such as 1 for the road) to make sure it works.
12+
#
13+
# Once it's working, modify the program so that the comprehension returns a list of tuples.
14+
# Each tuple consists of the location number and the description.
15+
#
16+
# Finally, wrap your comprehension in a for loop, and print the lists of all the locations that lead to each of the
17+
# other locations in turn.
18+
# In other words, use a for loop to run the comprehension for each of the keys in the locations dictionary.
19+
20+
21+
locations = {0: "You are sitting in front of a computer learning Python",
22+
1: "You are standing at the end of a road before a small brick building",
23+
2: "You are at the top of a hill",
24+
3: "You are inside a building, a well house for a small stream",
25+
4: "You are in a valley beside a stream",
26+
5: "You are in the forest"}
27+
28+
exits = {0: {"Q": 0},
29+
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
30+
2: {"N": 5, "Q": 0},
31+
3: {"W": 1, "Q": 0},
32+
4: {"N": 1, "W": 2, "Q": 0},
33+
5: {"W": 2, "S": 1, "Q": 0}}
34+
35+
# the_forest = [(key, locations[key]) for key, value in exits.items() if 5 in value.values()]
36+
# print(the_forest)
37+
38+
for key_loc, value_loc in locations.items():
39+
the_forest = [(key, locations[key]) for key, value in exits.items() if key_loc in value.values()]
40+
print(f"Location number {key_loc}\n\t{the_forest}")
41+
42+
# for key, value in exits.items():
43+
# if 5 in value.values():
44+
# print(f"Key: {key}, Desc: {locations[key]}")
45+
#
46+
# print(value.values())
47+
# print(f"Key: {key}\t|\tValue: {value}")
48+
# for key2, value2 in value.items():
49+
# print(f"\tKey2: {key2}\t|\tValue2: {value2}")
50+
51+
52+
# the_forest = [value for key, value in exits.items() if key == 5]
53+
# print(the_forest)
54+
55+
# meals = [meal for meal in menu if "spam" not in meal and "chicken" not in meal]
56+
# print(meals)
57+
# for key, value in available_parts.items():
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
locations = {0: "You are sitting in front of a computer learning Python",
2+
1: "You are standing at the end of a road before a small brick building",
3+
2: "You are at the top of a hill",
4+
3: "You are inside a building, a well house for a small stream",
5+
4: "You are in a valley beside a stream",
6+
5: "You are in the forest"}
7+
8+
exits = {0: {"Q": 0},
9+
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
10+
2: {"N": 5, "Q": 0},
11+
3: {"W": 1, "Q": 0},
12+
4: {"N": 1, "W": 2, "Q": 0},
13+
5: {"W": 2, "S": 1, "Q": 0}}
14+
15+
print("nested for loops")
16+
print("---")
17+
18+
for loc in sorted(locations):
19+
exits_to_destination_1 = []
20+
for ext in exits:
21+
if loc in exits[ext].values():
22+
exits_to_destination_1.append((ext, locations[ext]))
23+
print(f"Location leading to {loc}", end='\t')
24+
print(exits_to_destination_1)
25+
26+
print("---")
27+
28+
print("List comprehension inside a for loop")
29+
print("---")
30+
31+
for loc in sorted(locations):
32+
exits_to_destination_2 = [(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
33+
print(f"Location leading to {loc}", end='\t')
34+
print(exits_to_destination_2)
35+
36+
print("---")
37+
38+
print("Nested comprehension")
39+
40+
print("---")
41+
42+
exits_to_destination_3 = [[(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
43+
for loc in sorted(locations)]
44+
print(exits_to_destination_3)
45+
46+
print("---")
47+
48+
for index, loc in enumerate(exits_to_destination_3):
49+
print(f"Location leading to {index}", end='\t')
50+
print(loc)
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import timeit
2+
3+
setup = """\
4+
locations = {0: "You are sitting in front of a computer learning Python",
5+
1: "You are standing at the end of a road before a small brick building",
6+
2: "You are at the top of a hill",
7+
3: "You are inside a building, a well house for a small stream",
8+
4: "You are in a valley beside a stream",
9+
5: "You are in the forest"}
10+
11+
exits = {0: {"Q": 0},
12+
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
13+
2: {"N": 5, "Q": 0},
14+
3: {"W": 1, "Q": 0},
15+
4: {"N": 1, "W": 2, "Q": 0},
16+
5: {"W": 2, "S": 1, "Q": 0}}
17+
"""
18+
19+
print("nested for loops")
20+
print("---")
21+
nested_loop = """\
22+
for loc in sorted(locations):
23+
exits_to_destination_1 = []
24+
for ext in exits:
25+
if loc in exits[ext].values():
26+
exits_to_destination_1.append((ext, locations[ext]))
27+
print(f"Location leading to {loc}", end='\t')
28+
print(exits_to_destination_1)
29+
"""
30+
print("---")
31+
32+
print("List comprehension inside a for loop")
33+
print("---")
34+
loop_comp = """\
35+
for loc in sorted(locations):
36+
exits_to_destination_2 = [(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
37+
print(f"Location leading to {loc}", end='\t')
38+
print(exits_to_destination_2)
39+
"""
40+
print("---")
41+
42+
print("Nested comprehension")
43+
44+
print("---")
45+
nested_comp = """\
46+
exits_to_destination_3 = [[(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
47+
for loc in sorted(locations)]
48+
49+
for index, loc in enumerate(exits_to_destination_3):
50+
print(f"Location leading to {index}", end='\t')
51+
print(loc)
52+
"""
53+
54+
result_1 = timeit.timeit(nested_loop, setup, number=100000)
55+
result_2 = timeit.timeit(loop_comp, setup, number=100000)
56+
result_3 = timeit.timeit(nested_comp, setup, number=100000)
57+
print(f"Nested loop:\t{result_1}")
58+
print(f"Loop and comp:\t{result_2}")
59+
print(f"Nested comp:\t{result_3}")
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import timeit
2+
3+
setup = """\
4+
gc.enable()
5+
locations = {0: "You are sitting in front of a computer learning Python",
6+
1: "You are standing at the end of a road before a small brick building",
7+
2: "You are at the top of a hill",
8+
3: "You are inside a building, a well house for a small stream",
9+
4: "You are in a valley beside a stream",
10+
5: "You are in the forest"}
11+
12+
exits = {0: {"Q": 0},
13+
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
14+
2: {"N": 5, "Q": 0},
15+
3: {"W": 1, "Q": 0},
16+
4: {"N": 1, "W": 2, "Q": 0},
17+
5: {"W": 2, "S": 1, "Q": 0}}
18+
"""
19+
locations = {0: "You are sitting in front of a computer learning Python",
20+
1: "You are standing at the end of a road before a small brick building",
21+
2: "You are at the top of a hill",
22+
3: "You are inside a building, a well house for a small stream",
23+
4: "You are in a valley beside a stream",
24+
5: "You are in the forest"}
25+
26+
exits = {0: {"Q": 0},
27+
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
28+
2: {"N": 5, "Q": 0},
29+
3: {"W": 1, "Q": 0},
30+
4: {"N": 1, "W": 2, "Q": 0},
31+
5: {"W": 2, "S": 1, "Q": 0}}
32+
33+
34+
def nested_loop():
35+
result = []
36+
for loc in sorted(locations):
37+
exits_to_destination_1 = []
38+
for ext in exits:
39+
if loc in exits[ext].values():
40+
exits_to_destination_1.append((ext, locations[ext]))
41+
result.append(exits_to_destination_1)
42+
# print the result before returning
43+
for x in result:
44+
pass
45+
return result
46+
47+
48+
print("---")
49+
50+
51+
def loop_comp():
52+
result = []
53+
for loc in sorted(locations):
54+
exits_to_destination_2 = [(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
55+
result.append(exits_to_destination_2)
56+
# print the result before returning
57+
for x in result:
58+
pass
59+
return result
60+
61+
62+
print("---")
63+
64+
65+
def nested_comp():
66+
exits_to_destination_3 = [[(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
67+
for loc in sorted(locations)]
68+
# print the result before returning
69+
for x in exits_to_destination_3:
70+
pass
71+
return exits_to_destination_3
72+
73+
74+
def nested_gen():
75+
exits_to_destination_3 = ([(ext, locations[ext]) for ext in exits if loc in exits[ext].values()]
76+
for loc in sorted(locations))
77+
# print the result before returning
78+
for x in exits_to_destination_3:
79+
pass
80+
return exits_to_destination_3
81+
82+
83+
# print(nested_loop())
84+
# print(loop_comp())
85+
# print(nested_comp())
86+
87+
result_1 = timeit.timeit(nested_loop, setup, number=100000)
88+
result_2 = timeit.timeit(loop_comp, setup, number=100000)
89+
result_3 = timeit.timeit(nested_comp, setup, number=100000)
90+
result_4 = timeit.timeit(nested_gen, setup, number=100000)
91+
print(f"Nested loop:\t{result_1}")
92+
print(f"Loop and comp:\t{result_2}")
93+
print(f"Nested comp:\t{result_3}")
94+
print(f"Nested gen:\t\t{result_4}")
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Create a new Python file - I've called this one "fizzbuzz.py".
2+
#
3+
# Use the conditional expression from the previous video to produce
4+
# a list comprehension that returns the fizzbuzz results.
5+
#
6+
# If a number's divisible by 3, the value should be "fizz".
7+
# If it's divisible by 5, the value should be "buzz".
8+
# If it's divisible by both 3 and 5, the value should be "fizz buzz"
9+
# Finally, if none of those conditions apply, the value will be the number itself.
10+
#
11+
# The code from the end of the last video appears below, so you can check the result.
12+
13+
for x in range(1, 31):
14+
fizzbuzz = "fizz buzz" if x % 15 == 0 else "fizz" if x % 3 == 0 else "buzz" if x % 5 == 0 else str(x)
15+
print(fizzbuzz)
16+
17+
fizz_list = ["fizz buzz" if x % 15 == 0 else "fizz" if x % 3 == 0 else "buzz" if x % 5 == 0 else str(x)
18+
for x in range(1, 31)]
19+
print(fizz_list)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
burgers = ["beef", "chicken", "spicy bean"]
2+
toppings = {"cheese", "egg", "beans", "spam"}
3+
4+
meals = [(burger, topping) for burger in burgers for topping in toppings]
5+
print(meals)
6+
7+
print("---")
8+
9+
for meals in [(burger, topping) for burger in burgers for topping in toppings]:
10+
print(meals)
11+
12+
print("---")
13+
14+
for burger in burgers:
15+
for topping in toppings:
16+
print((burger, topping))
17+
18+
print("---")
19+
20+
for nested_meals in [[(burger, topping) for burger in burgers] for topping in toppings]:
21+
print(nested_meals)
22+
23+
print("---")
24+
25+
for nested_meals in [[(burger, topping) for topping in toppings] for burger in burgers]:
26+
print(nested_meals)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# In an early video, we used a for loop to print the times tables, for values from 1 to 10.
2+
# That was a nested loop, which appears below.
3+
#
4+
# The challenge is to use a nested comprehension, to produce the same values.
5+
# You can iterate over the list, to produce the same output as the for loop, or just print out the list.
6+
7+
for i in range(1, 11):
8+
for j in range(1, 11):
9+
print(i, i * j)
10+
11+
i_range = range(1, 11)
12+
j_range = range(1, 11)
13+
14+
nested_numbers = [[(i, i * j) for j in j_range] for i in i_range]
15+
print(nested_numbers)
16+
17+
print("---")
18+
19+
times = [(i, i * j) for i in range(1, 11) for j in range(1, 11)]
20+
print(times)
21+
22+
print("---")
23+
24+
for x, y in [(i, i * j) for i in range(1, 11) for j in range(1, 11)]:
25+
print(x, y)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# In the section on Functions, we looked at 2 different ways to calculate the factorial
2+
# of a number. We used an iterative approach, and also used a recursive function.
3+
#
4+
# This challenge is to use the timeit module to see which performs better.
5+
#
6+
# The two functions appear below.
7+
#
8+
# Hint: change the number of iterations to 1,000 or 10,000. The default
9+
# of one million will take a long time to run.
10+
11+
import timeit
12+
13+
fact_test = """\
14+
def fact(n):
15+
result = 1
16+
if n > 1:
17+
for f in range(2, n + 1):
18+
result *= f
19+
return result
20+
21+
22+
x = fact(130)
23+
"""
24+
25+
factorial_test = """\
26+
def factorial(n):
27+
# n! can also be defined as n * (n-1)!
28+
if n <= 1:
29+
return 1
30+
else:
31+
return n * factorial(n-1)
32+
33+
34+
y = factorial(130)
35+
"""
36+
37+
print(timeit.timeit(fact_test, number=10000))
38+
print(timeit.timeit(factorial_test, number=10000))

0 commit comments

Comments
 (0)