8000 Merge pull request #8 from tecladocode/lambda_function_improvements · coding794/complete-python-course@d5a1ef1 · GitHub
[go: up one dir, main page]

Skip to content

Commit d5a1ef1

Browse files
authored
Merge pull request tecladocode#8 from tecladocode/lambda_function_improvements
Add improvements as discussed with Phil
2 parents 2bb8298 + 9df8eb8 commit d5a1ef1

File tree

9 files changed

+124
-52
lines changed
  • course_contents
    • 10_advanced_python/lectures/16_higher_order_functions
    • 2_intro_to_python/lectures

9 files changed

+124
-52
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
# `before_and_after` is a higher-order function. That just means it's a function which has another function as a parameter.
3+
def before_and_after(func): # func is a function passed
4+
print("Before...")
5+
func()
6+
print("After...")
7+
8+
9+
# greet, not greet(). That's because we're passing the function, not the result of calling the function.
10+
before_and_after(greet)
11+
12+
13+
# Another example
14+
15+
16+
movies = [
17+
{"name": "The Matrix", "director": "Wachowski"},
18+
{"name": "A Beautiful Day in the Neighborhood", "director": "Heller"},
19+
{"name": "The Irishman", "director": "Scorsese"},
20+
{"name": "Klaus", "director": "Pablos"},
21+
{"name": "1917", "director": "Mendes"},
22+
]
23+
24+
25+
def find_movie(expected, finder):
26+
found = []
27+
for movie in movies:
28+
if finder(movie) == expected:
29+
found.append(movie)
30+
return found
31+
32+
33+
find_by = input("What property are we searching by? ")
34+
looking_for = input("What are you looking for? ")
35+
movie = find_movie(looking_for, lambda x: x[find_by])
36+
print(movie or 'No movies found.')
37+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# https://blog.tecladocode.com/python-enumerate/
2+
3+
friends = ["Rolf", "John", "Anna"]
4+
5+
for counter, friend in enumerate(friends, start=1):
6+
print(counter, friend)
7+
8+
# 1 Rolf
9+
# 2 John
10+
# 3 Anna
11+
12+
13+
friends = ["Rolf", "John", "Anna"]
14+
print(list(enumerate(friends))) # [(0, 'Rolf'), (1, 'John'), (2, 'Anna')]
15+
print(dict(enumerate(friends))) # {0: 'Rolf', 1: 'John', 2: 'Anna'}

course_contents/2_intro_to_python/lectures/19_first_class_higher_order_functions/code.py

Lines changed: 0 additions & 52 deletions
This file was deleted.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# In Python, functions are first class citizens.
2+
# That means that, just like any other value, they can be passed as arguments to functions or assigned to variables.
3+
# Here's a simple (yet not terribly useful) example to illustrate it:
4+
5+
6+
def greet():
7+
print("Hello!")
8+
9+
10+
hello = greet # hello is another name for the greet function now.
11+
12+
hello()
13+
14+
# Let's move on to a more useful example.
15+
16+
# These don't _have_ to be lambdas. They could be normal functions too!
17+
# I'm making them lambdas because they're really short.
18+
19+
avg = lambda seq: sum(seq) / len(seq)
20+
total = lambda seq: sum(seq) # could just be `sum`
21+
top = lambda seq: max(seq) # could just be `max`
22+
23+
students = [
24+
{"name": "Rolf", "grades": (67, 90, 95, 100)},
25+
{"name": "Bob", "grades": (56, 78, 80, 90)},
26+
{"name": "Jen", "grades": (98, 90, 95, 99)},
27+
{"name": "Anne", "grades": (100, 100, 95, 100)},
28+
]
29+
30+
for student in students:
31+
name = student["name"]
32+
grades = student["grades"]
33+
34+
print(f"Student: {name}")
35+
operation = input("Enter 'average', 'total', or 'top': ")
36+
37+
if operation == "average":
38+
print(avg(grades))
39+
elif operation == "total":
40+
print(total(grades))
41+
elif operation == "top":
42+
print(top(grades))
43+
44+
# Here, you can see how we can store functions inside a dictionary—just as we could do with numbers, strings, or any other type of data.
45+
# We're creating a dictionary of what would be user input to the function that we want to run in each case.
46+
47+
operations = {
48+
"average": avg,
49+
"total": total, # could just be `sum`
50+
"top": top, # could just be `max`
51+
}
52+
53+
# The `operations` dictionary could also be defined inline:
54+
55+
operations = {
56+
"average": lambda seq: sum(seq) / len(seq),
57+
"total": lambda seq: sum(seq), # could just be `sum`
58+
"top": lambda seq: max(seq), # could just be `max`
59+
}
60+
61+
# The rest of the code can make use of the `operations` dictionary
62+
63+
for student in students:
64+
name = student["name"]
65+
grades = student["grades"]
66+
67+
print(f"Student: {name}")
68+
operation = input("Enter 'average', 'total', or 'top': ")
69+
operation_function = operations[operation] # This means we don't need an if statement (but could get errors!)
70+
71+
print(operation_function(grades))
72+

0 commit comments

Comments
 (0)
0