Created
May 9, 2025 02:41
-
-
Save nrrb/44f2655a27d3f42f7a51483fcce04093 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# singleton.py | |
class Logger: | |
"""Simple singleton logger.""" | |
_instance = None | |
def __new__(cls): | |
if cls._instance is None: | |
cls._instance = super().__new__(cls) | |
cls._instance.logs = [] | |
return cls._instance | |
def log(self, msg): | |
self.logs.append(msg) | |
print(f"[LOG] {msg}") | |
# recursion.py | |
def factorial(n): | |
"""Classic recursion.""" | |
logger = Logger() | |
logger.log(f"factorial({n})") | |
if n <= 1: | |
return 1 | |
return n * factorial(n - 1) | |
# mutual_recursion.py | |
def is_even(n): | |
"""Mutual recursion with is_odd.""" | |
logger = Logger() | |
logger.log(f"is_even({n})") | |
if n == 0: | |
return True | |
return is_odd(n - 1) | |
def is_odd(n): | |
logger = Logger() | |
logger.log(f"is_odd({n})") | |
if n == 0: | |
return False | |
return is_even(n - 1) | |
# callbacks.py | |
def apply_callback(cb, value): | |
"""Call any function cb on value.""" | |
return cb(value) | |
# closures.py | |
def make_multiplier(factor): | |
"""Return a callback that multiplies by factor.""" | |
def multiplier(x): | |
return x * factor | |
return multiplier | |
# cycle.py | |
def f1(x): | |
logger = Logger() | |
logger.log(f"f1({x}) → f2({x + 1})") | |
return f2(x + 1) | |
def f2(x): | |
logger = Logger() | |
logger.log(f"f2({x}) → f3({x * 2})") | |
return f3(x * 2) | |
def f3(x): | |
logger = Logger() | |
logger.log(f"f3({x}) → f1({x - 3}) or back") | |
if x > 50: | |
return x | |
return f1(x - 3) | |
# generator.py | |
def countdown(n): | |
"""A simple generator.""" | |
while n > 0: | |
Logger().log(f"yielding {n}") | |
yield n | |
n -= 1 | |
yield "done" | |
def doit(): | |
logger = Logger() | |
logger.log("Starting main") | |
# 1. Recursion | |
print("5! =", factorial(5)) | |
# 2. Mutual recursion | |
for i in range(5): | |
print(i, "is_even?", is_even(i)) | |
# 3. Callbacks & closures | |
doubler = make_multiplier(2) | |
print("Double 7 via apply_callback:", apply_callback(doubler, 7)) | |
print("Square 4 directly:", apply_callback(lambda x: x*x, 4)) | |
# 4. Three‐function cycle (stops when >50) | |
result = f1(10) | |
print("Cycle result:", result) | |
# 5. Generator usage | |
for item in countdown(3): | |
print("countdown:", item) | |
logger.log("Main finished") | |
if __name__ == "__main__": | |
doit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment