-
Notifications
You must be signed in to change notification settings - Fork 2k
Solution #2201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Solution #2201
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,36 @@ | ||
| from typing import Callable | ||
| from functools import wraps | ||
| from typing import Callable, Any, List | ||
|
|
||
|
|
||
| def cache(func: Callable) -> Callable: | ||
| # Write your code here | ||
| pass | ||
| stored_results = {} | ||
|
|
||
| @wraps(func) | ||
| def wrapper(*args, **kwargs) -> Any: | ||
| key = (args, tuple(sorted(kwargs.items()))) | ||
| if key in stored_results: | ||
| print("Getting from cache") | ||
| return stored_results[key] | ||
| print("Calculating new result") | ||
| stored_results[key] = func(*args, **kwargs) | ||
| return stored_results[key] | ||
|
|
||
| return wrapper | ||
|
|
||
|
|
||
| @cache | ||
| def long_time_func(base: int, power: int, mod: int) -> int: | ||
| return (base ** power ** mod) % (base * mod) | ||
|
|
||
|
|
||
| @cache | ||
| def long_time_func_2(n_tuple: tuple, power: int) -> List[int]: | ||
| return [number ** power for number in n_tuple] | ||
|
|
||
|
|
||
| long_time_func(1, 2, 3) | ||
| long_time_func(2, 2, 3) | ||
| long_time_func_2((5, 6, 7), 5) | ||
| long_time_func(1, 2, 3) | ||
| long_time_func_2((5, 6, 7), 10) | ||
| long_time_func_2((5, 6, 7), 10) | ||
|
Comment on lines
+31
to
+36
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This violates the checklist item: "2. Add comments, prints, and functions to check your solution when you write your code. Don't forget to delete them when you are ready to commit and push your code." The calls at module level cause side effects on import. Move or wrap these demonstration calls (lines 31–36) inside an |
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These calls run at import time and produce side effects. Remove these demonstration calls or move them under an
if __name__ == "__main__":guard so the module has no side effects on import. This violates the checklist item: "Add comments, prints, and functions to check your solution when you write your code. Don't forget to delete them when you are ready to commit and push your solution."