You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here is a function that returns all the factors for a given integer. Note how I'm making use of the `cache` decorator, in order to cache the factors of any integer that has been seen before.
86
+
87
+
```python
88
+
@cache
89
+
defget_factors(num: int) -> set[int]:
90
+
""" Gets the factors for a given number. Returns a set[int] of factors.
91
+
# E.g. when num=8, factors will be 1, 2, 4, 8 """
92
+
factors =set()
93
+
94
+
# Iterate from 1 to sqrt of 8,
95
+
# since a larger factor of num must be a multiple of a smaller factor already checked
96
+
for i inrange(1, int(num**0.5) +1): # e.g. with num=8, this is range(1, 3)
97
+
if num % i ==0: # if it is a factor, then dividing num by it will yield no remainder
98
+
factors.add(i) # e.g. 1, 2
99
+
factors.add(num//i) # i.e. 8//1 = 8, 8//2 = 4
100
+
101
+
return factors
102
+
```
103
+
104
+
## To Base-N
105
+
106
+
This function returns the string representation of an integer, after conversion to any arbitrary base.
107
+
108
+
```python
109
+
defto_base_n(number: int, base: int):
110
+
""" Convert any integer number into a base-n string representation of that number.
111
+
E.g. to_base_n(38, 5) = 123
112
+
113
+
Args:
114
+
number (int): The number to convert
115
+
base (int): The base to apply
116
+
117
+
Returns:
118
+
[str]: The string representation of the number
119
+
"""
120
+
ret_str =""
121
+
curr_num = number
122
+
while curr_num:
123
+
ret_str =str(curr_num % base) + ret_str
124
+
curr_num //= base
125
+
126
+
return ret_str if number >0else"0"
127
+
```
128
+
129
+
## Timer Decorator
130
+
131
+
A Python **decorator** is essentially a function that is used to modify or extend the behavior of other functions or methods. It allows for the addition of functionality to an existing piece of code without changing its structure. This is particularly useful for code reusability, separation of concerns, and adhering to the DRY (Don't Repeat Yourself) principle.
132
+
133
+
In Python, decorators are applied by prefixing a function definition with `@decorator-name`. When a function is decorated, it is passed to the decorator as an argument, and the decorator returns a new function with the enhanced functionality.
134
+
135
+
I found myself writing this code all the time:
136
+
137
+
```python
138
+
if__name__=="__main__":
139
+
t1 = time.perf_counter()
140
+
main()
141
+
t2 = time.perf_counter()
142
+
print(f"Execution time: {t2 - t1:0.4f} seconds")
143
+
```
144
+
145
+
I figured... this is a great candidate for a decorator! And here it is:
146
+
147
+
```python
148
+
@contextlib.contextmanager
149
+
deftimer(description="Execution time"):
150
+
"""A context manager to measure the time taken by a block of code or function.
151
+
152
+
Args:
153
+
- description (str): A description for the timing output.
- I use an existing decorator - `@contextlib.contextmanager` - to turn my function into a resource that we can invoke using the `with` statement.
165
+
- Inside the function:
166
+
-`t1` is set to the current time using `time.perf_counter()`.
167
+
- The `yield` statement pauses the function, allowing the block of code within the `with` statement to execute. The context manager waits at this point until the block completes its execution.
168
+
- After the block inside the `with` statement finishes, execution resumes in the `timer` function. `t2` is set to the current time, again using `time.perf_counter()`.
169
+
- The function then calculates the duration the code block took to execute by subtracting `t1` from `t2`. This duration is then logged with the provided description.
170
+
171
+
So now, I can use the `timer` decorator like this:
0 commit comments