Skip to content

Commit 85bfe79

Browse files
committed
Improve code
1 parent 65e93db commit 85bfe79

File tree

18 files changed

+84
-53
lines changed

18 files changed

+84
-53
lines changed

python_utils/decorator/decorator_as_class.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import functools
22

33
# The typical way to maintain state in Python is by using classes.
4-
# Recall that the decorator syntax @decorator is just a quicker way of saying func = decorator(func).
5-
# Therefore, if decorator is a class, it needs to take func as an argument in its .__init__() initializer.
4+
# Recall that the decorator syntax @decorator is just a quicker way of saying func = decorator(func).
5+
# Therefore, if decorator is a class, it needs to take func as an argument in its .__init__() initializer.
66
# Furthermore, the class instance needs to be callable so that it can stand in for the decorated function.
77
# For a class instance to be callable, you implement the special .__call__() method.
88
# The .__call__() method is executed each time you try to call an instance of the class:
99

10+
1011
class CountCalls:
1112
def __init__(self, func):
1213
functools.update_wrapper(self, func)
@@ -18,9 +19,11 @@ def __call__(self, *args, **kwargs):
1819
print(f"Call {self.num_calls} of {self.func.__name__}()")
1920
return self.func(*args, **kwargs)
2021

22+
2123
@CountCalls
2224
def say_hi():
2325
print("Hi!")
2426

27+
2528
for i in range(4):
26-
say_hi()
29+
say_hi()
Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import time
22
import functools
33

4-
# The @functools.wraps decorator uses functools.update_wrapper() to update
4+
# The @functools.wraps decorator uses functools.update_wrapper() to update
55
# special attributes like __name__ and __doc__ that are used in the introspection.
66

7+
78
def duration(func):
89
"""Print the runtime of the decorated function"""
910
@functools.wraps(func)
@@ -16,6 +17,7 @@ def wrapper(*args, **kwargs):
1617
return res
1718
return wrapper
1819

20+
1921
def do_twice(func):
2022
"""Call twice the decorated function"""
2123
@functools.wraps(func)
@@ -25,29 +27,33 @@ def wrapper(*args, **kwargs):
2527
# return res
2628
return wrapper
2729

30+
2831
@duration
2932
def soma():
30-
total=0
31-
for i in range(0,1000):
32-
total+=i
33+
total = 0
34+
for i in range(1000):
35+
total += i
3336
return total
3437

38+
3539
@duration
3640
def multiplicacao():
37-
total=1
38-
for i in range(1,1000):
39-
total*=i
41+
total = 1
42+
for i in range(1, 1000):
43+
total *= i
44+
4045

4146
# Nesting decorators
4247
@do_twice
4348
@duration
4449
def twice_multiplicacao():
45-
total=1
46-
for i in range(1,1000):
47-
total*=i
50+
total = 1
51+
for i in range(1, 1000):
52+
total *= i
53+
4854

4955
print(soma())
50-
print(f'-------------------------------------')
56+
print('-------------------------------------')
5157
print(multiplicacao())
52-
print(f'-------------------------------------')
53-
print(twice_multiplicacao())
58+
print('-------------------------------------')
59+
print(twice_multiplicacao())

python_utils/decorator/examples/caching.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import functools
22
from count_calls import CountCalls
33

4+
45
def cache(func):
56
"""Keep a cache of previous function calls"""
67
@functools.wraps(func)
@@ -12,20 +13,23 @@ def wrapper_cache(*args, **kwargs):
1213
wrapper_cache.cache = {}
1314
return wrapper_cache
1415

16+
1517
@CountCalls
1618
def fibonacci_straightforward(num):
1719
if num < 2:
1820
return num
1921
return fibonacci_straightforward(num - 1) + fibonacci_straightforward(num - 2)
2022

23+
2124
@cache
2225
@CountCalls
2326
def fibonacci_memoization(num):
2427
if num < 2:
2528
return num
2629
return fibonacci_memoization(num - 1) + fibonacci_memoization(num - 2)
2730

28-
n=8
31+
32+
n = 8
2933
print(fibonacci_straightforward(n))
30-
print(f'----------------------------------')
31-
print(fibonacci_memoization(n))
34+
print('----------------------------------')
35+
print(fibonacci_memoization(n))

python_utils/decorator/examples/count_calls.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import functools
22

33
# The typical way to maintain state in Python is by using classes.
4-
# Recall that the decorator syntax @decorator is just a quicker way of saying func = decorator(func).
5-
# Therefore, if decorator is a class, it needs to take func as an argument in its .__init__() initializer.
4+
# Recall that the decorator syntax @decorator is just a quicker way of saying func = decorator(func).
5+
# Therefore, if decorator is a class, it needs to take func as an argument in its .__init__() initializer.
66
# Furthermore, the class instance needs to be callable so that it can stand in for the decorated function.
77
# For a class instance to be callable, you implement the special .__call__() method.
88
# The .__call__() method is executed each time you try to call an instance of the class:
99

10+
1011
class CountCalls:
1112
def __init__(self, func):
1213
functools.update_wrapper(self, func)
@@ -18,9 +19,11 @@ def __call__(self, *args, **kwargs):
1819
print(f"Call {self.num_calls} of {self.func.__name__}()")
1920
return self.func(*args, **kwargs)
2021

22+
2123
@CountCalls
2224
def say_hi():
2325
print("Hi!")
2426

27+
2528
for i in range(4):
26-
say_hi()
29+
say_hi()

python_utils/decorator/examples/countdown.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import functools
22
import time
33

4+
45
def slow_down(_func=None, *, rate=1):
56
"""Sleep given amount of seconds before calling the function"""
67
def decorator_slow_down(func):
@@ -15,6 +16,7 @@ def wrapper_slow_down(*args, **kwargs):
1516
else:
1617
return decorator_slow_down(_func)
1718

19+
1820
@slow_down(rate=1)
1921
def countdown(from_number):
2022
if from_number < 1:
@@ -23,4 +25,5 @@ def countdown(from_number):
2325
print(from_number)
2426
countdown(from_number - 1)
2527

26-
countdown(3)
28+
29+
countdown(3)
Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import functools
22

3+
34
def singleton(cls):
45
"""Make a class a Singleton class (only one instance)"""
56
@functools.wraps(cls)
@@ -10,12 +11,14 @@ def wrapper_singleton(*args, **kwargs):
1011
wrapper_singleton.instance = None
1112
return wrapper_singleton
1213

14+
1315
@singleton
1416
class Foo:
1517
pass
1618

19+
1720
first_one = Foo()
1821
another_one = Foo()
19-
print(f'{first_one = }')
20-
print(f'{another_one = }')
21-
print(f'first_one is another_one: {first_one is another_one}')
22+
print(f'{first_one=}')
23+
print(f'{another_one=}')
24+
print(f'first_one is another_one: {first_one is another_one}')
Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1-
# List Comprehension
2-
## List comprehension in Python are constructed as follows:
3-
lst = [i for i in range(0,6)]
1+
""" List Comprehension """
2+
# List comprehension in Python are constructed as follows:
3+
lst = [i for i in range(6)]
44
print(lst)
55

6-
## Sum 2 in each list item
6+
# Sum 2 in each list item
77
res = []
88
for i in lst:
99
res.append(i+2)
1010
print(res)
1111

12-
## Sum 2 in each list item using list comprehensions
12+
# Sum 2 in each list item using list comprehensions
1313
res = [i+2 for i in lst]
1414
print(res)
1515

16-
## Sum 2 in each even list item using list comprehensions
17-
res = [i+2 if i%2==0 and i!=0 else i for i in lst]
18-
print(res)
16+
# Sum 2 in each even list item using list comprehensions
17+
res = [i+2 if i % 2 == 0 and i != 0 else i for i in lst]
18+
print(res)

python_utils/pdb/example2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ def get_path(filename):
1111

1212

1313
filename = __file__
14-
print(f'path = {get_path(filename)}')
14+
print(f'path = {get_path(filename)}')

python_utils/pdb/example3.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ def get_path(filename):
1212
filename = __file__
1313
breakpoint()
1414
filename_path = get_path(filename)
15-
print(f'path = {filename_path}')
15+
print(f'path = {filename_path}')

python_utils/pdb/example4.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@
55
filename = __file__
66
breakpoint()
77
filename_path = util.get_path(filename)
8-
print(f'path = {filename_path}')
8+
print(f'path = {filename_path}')

python_utils/pdb/example5.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@ def get_path(fname):
1414

1515
filename = __file__
1616
filename_path = get_path(filename)
17-
print(f'path = {filename_path}')
17+
print(f'path = {filename_path}')

python_utils/pdb/example6.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,4 @@ def get_file_info(full_fname):
1010

1111
filename = __file__
1212
filename_path = get_file_info(filename)
13-
print(f'path = {filename_path}')
13+
print(f'path = {filename_path}')

python_utils/pdb/fileutil.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ def get_path(fname):
33
import os
44
breakpoint()
55
head, tail = os.path.split(fname)
6-
return head
6+
return head

python_utils/pdb/util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ def get_path(filename):
22
"""Return file's path or empty string if no path."""
33
import os
44
head, tail = os.path.split(filename)
5-
return head
5+
return head

python_utils/walrus_operator/walrus_operator.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
}
2121
print(description)
2222

23-
'''The variables num_length and num_sum are only used to optimize the calculations
23+
'''The variables num_length and num_sum are only used to optimize the calculations
2424
inside the dictionary. By using the walrus operator, you can make this role clearer'''
2525
description = {
2626
"length": (num_length := len(numbers)),
@@ -34,11 +34,13 @@
3434
'''Here, you filter the numbers list and leave the positive results from applying slow().
3535
The problem with this code is that this expensive function is called twice.
3636
'''
37+
numbers = [7, 6, 1, 4, 1, 8, 0, 6]
38+
39+
3740
def slow(x):
3841
return x-2
3942

4043

41-
numbers = [7, 6, 1, 4, 1, 8, 0, 6]
4244
results = [slow(num) for num in numbers if slow(num) > 0]
4345
print(results)
4446

@@ -49,8 +51,8 @@ def slow(x):
4951
print(results)
5052

5153

52-
'''Here, you first capture all city names that start with "B".
53-
Then, if there’s at least one such city name, you print out the
54+
'''Here, you first capture all city names that start with "B".
55+
Then, if there’s at least one such city name, you print out the
5456
first city name starting with "B".'''
5557
cities = ['Monaco', 'Vancouver', 'Rio de Janeiro', 'Berlin', 'La Paz', 'Bogota', 'Dallas']
5658

@@ -61,6 +63,8 @@ def slow(x):
6163

6264
'''You can more clearly see what’s happening by wrapping .startswith("B") in a function that
6365
also prints out which item is being checked:'''
66+
67+
6468
def starts_with_b(name):
6569
print(f"Checking {name}: {(result := name.startswith('B'))}")
6670
return result

python_utils/yield/example_1.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ def random_numbers():
22
for i in range(10):
33
yield i
44

5-
gen = random_numbers()
65

7-
print(next(gen))
8-
print(next(gen))
9-
print(next(gen))
10-
print(next(gen))
11-
print(list(gen))
6+
if __name__ == '__main__':
7+
gen = random_numbers()
8+
9+
print(next(gen))
10+
print(next(gen))
11+
print(next(gen))
12+
print(next(gen))
13+
print(list(gen))

python_utils/yield/example_2.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,18 @@ def random_numbers():
22
for i in range(3):
33
yield i
44

5+
56
def random_numbers_100():
6-
for i in range(100,105):
7+
for i in range(100, 105):
78
yield i
89

10+
911
def generator():
1012
yield from random_numbers()
1113
print('Next generator')
1214
yield from random_numbers_100()
1315

16+
1417
if __name__ == '__main__':
1518
gen = generator()
1619
print(next(gen))

solutions/buildings/build.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def bfs(w, h, area):
2626
if (newx >= w) | (newy >= h) | (newx < 0) | (newy < 0):
2727
continue
2828

29-
if(dist[newx][newy] == -1):
29+
if (dist[newx][newy] == -1):
3030
dist[newx][newy] = dist[x][y] + 1
3131
q.append([newx, newy])
3232

0 commit comments

Comments
 (0)