-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'master' into python-protocol
- Loading branch information
Showing
27 changed files
with
376 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Python's Built-in Functions: A Complete Exploration | ||
|
||
This folder provides the code examples for the Real Python tutorial [Python's Built-in Functions: A Complete Exploration](https://realpython.com/python-built-in-functions/). |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
class Duck: | ||
def fly(self): | ||
print("The duck is flying") | ||
|
||
def swim(self): | ||
print("The duck is swimming") | ||
|
||
|
||
class Pigeon: | ||
def fly(self): | ||
print("The pigeon is flying") |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
functions = [ | ||
"def add(a, b): return a + b", | ||
"def subtract(a, b): return a - b", | ||
"def multiply(a, b): return a * b", | ||
"def divide(a, b): return a / b", | ||
] | ||
|
||
|
||
for function in functions: | ||
exec(function) | ||
|
||
|
||
# Uncomment the following lines | ||
# print(add(1, 2)) | ||
# print(subtract(3, 2)) | ||
# print(multiply(2, 3)) | ||
# print(divide(6, 3)) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
from time import sleep | ||
|
||
SENTINEL = object() | ||
|
||
|
||
class Circle: | ||
def __init__(self, radius): | ||
self.radius = radius | ||
self._diameter = SENTINEL | ||
|
||
@property | ||
def diameter(self): | ||
if self._diameter is SENTINEL: | ||
sleep(0.5) # Simulate a costly computation | ||
self._diameter = self.radius * 2 | ||
return self._diameter | ||
|
||
|
||
circle = Circle(5) | ||
print(circle.diameter) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
class CommandProcessor: | ||
def __init__(self): | ||
self.commands = {} | ||
|
||
def register_command(self, command): | ||
if not callable(command): | ||
raise ValueError("command is not callable") | ||
self.commands[command.__name__] = command | ||
|
||
def execute_command(self, name, *args, **kwargs): | ||
if (command := self.commands.get(name)) is None: | ||
raise ValueError(f"command '{name}' not found") | ||
return command(*args, **kwargs) | ||
|
||
|
||
def add(a, b): | ||
return a + b | ||
|
||
|
||
subtract = 3 - 2 | ||
|
||
|
||
command_processor = CommandProcessor() | ||
command_processor.register_command(add) | ||
command_processor.register_command(subtract) | ||
|
||
print(command_processor.execute_command("add", 1, 2)) | ||
print(command_processor.register_command(subtract)) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"DATABASE_URL": "postgres://user:pass@localhost/dbname", | ||
"DEBUG_MODE": true, | ||
"MAX_CONNECTIONS": 10 | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import json | ||
|
||
|
||
def load_config(config_file): | ||
with open(config_file) as file: | ||
config = json.load(file) | ||
|
||
globals().update(config) | ||
|
||
|
||
load_config("config.json") | ||
print(globals()) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
def evaluator(expression): | ||
numbers = [2, 3, 4, 5] | ||
n = len(numbers) | ||
return eval(expression, {}, {"numbers": numbers, "n": n}) | ||
|
||
|
||
print(evaluator("sum(numbers) / n + 100")) # 3.5 |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
def create_class(name, custom_members): | ||
def __init__(self, **kwargs): | ||
self.__dict__.update(kwargs) | ||
|
||
def __repr__(self): | ||
return f"{name}({self.__dict__})" | ||
|
||
class_members = { | ||
"__init__": __init__, | ||
"__repr__": __repr__, | ||
} | ||
class_members.update(custom_members) | ||
|
||
return type(name, (), class_members) | ||
|
||
|
||
User = create_class("User", {"name": "", "age": 0, "email": ""}) | ||
Product = create_class("Product", {"name": "", "price": 0.0, "units": 0}) | ||
|
||
john = User(name="John", age=30, email="[email protected]") | ||
table = Product(name="Table", price=200.0, units=5) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
class Fibonacci: | ||
def __init__(self): | ||
self._cache = [0, 1] | ||
|
||
def __call__(self, index): | ||
if index < len(self._cache): | ||
fib_number = self._cache[index] | ||
print(f"{fib_number} id = {id(fib_number)}") | ||
else: | ||
fib_number = self(index - 1) + self(index - 2) | ||
self._cache.append(fib_number) | ||
return fib_number |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
with open("fruits.txt") as file: | ||
print(file.read()) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
class Formatter: | ||
@staticmethod | ||
def as_currency(value): | ||
return f"${value:,.2f}" | ||
|
||
@staticmethod | ||
def as_percent(value): | ||
return f"{value:.2%}" |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from random import randint | ||
|
||
LOW, HIGH = 1, 10 | ||
|
||
secret_number = randint(LOW, HIGH) | ||
clue = "" | ||
|
||
while True: | ||
guess = input(f"Guess a number between {LOW} and {HIGH} {clue} ") | ||
number = int(guess) | ||
if number > secret_number: | ||
clue = f"(less than {number})" | ||
elif number < secret_number: | ||
clue = f"(greater than {number})" | ||
else: | ||
break | ||
|
||
print(f"You guessed it! The secret number is {number}") |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
def mean(values): | ||
try: | ||
return sum(values) / len(values) | ||
except ZeroDivisionError: | ||
raise ValueError("mean() arg shouldn't be empty") from None |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
def list_menu(options): | ||
print("Main Menu:") | ||
for index, option in enumerate(options, start=1): | ||
print(f"{index}. {option}") | ||
|
||
|
||
# Example usage | ||
menu_options = ["Open", "Save", "Settings", "Quit"] | ||
list_menu(menu_options) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
class Person: | ||
def __init__(self, name, age): | ||
self.name = name | ||
self.age = age | ||
|
||
|
||
jane = Person("Jane", 25) | ||
print(getattr(jane, "name")) | ||
print(getattr(jane, "age")) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import math | ||
|
||
|
||
class Point: | ||
def __init__(self, x, y): | ||
self.x = x | ||
self.y = y | ||
|
||
@classmethod | ||
def from_polar(cls, distance, angle): | ||
return cls( | ||
x=distance * math.cos(math.radians(angle)), | ||
y=distance * math.sin(math.radians(angle)), | ||
) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# class Point: | ||
# def __init__(self, x, y): | ||
# self.x = x | ||
# self.y = y | ||
|
||
|
||
class Point: | ||
def __init__(self, x, y): | ||
self.set_x(x) | ||
self.set_y(y) | ||
|
||
def get_x(self): | ||
return self._x | ||
|
||
def set_x(self, x): | ||
self._x = self.validate(x) | ||
|
||
def get_y(self): | ||
return self._y | ||
|
||
def set_y(self, y): | ||
self._y = self.validate(y) | ||
|
||
def validate(self, value): | ||
if not isinstance(value, int | float): | ||
raise ValueError("coordinates must be numbers") | ||
return value |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
class Point: | ||
def __init__(self, x, y): | ||
self.x = x | ||
self.y = y | ||
|
||
@property | ||
def x(self): | ||
return self._x | ||
|
||
@x.setter | ||
def x(self, value): | ||
self._x = self.validate(value) | ||
|
||
@property | ||
def y(self): | ||
return self._y | ||
|
||
@y.setter | ||
def y(self, value): | ||
self._y = self.validate(value) | ||
|
||
def validate(self, value): | ||
if not isinstance(value, int | float): | ||
raise ValueError("coordinates must be numbers") | ||
return value |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import timeit | ||
|
||
base = 2 | ||
exp = 1000000 | ||
mod = 1000000 | ||
|
||
print( | ||
timeit.timeit("pow(base, exp) % mod", globals=globals(), number=10) * 1000 | ||
) | ||
|
||
print( | ||
timeit.timeit("pow(base, exp, mod)", globals=globals(), number=10) * 1000 | ||
) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import csv | ||
import json | ||
|
||
|
||
class CSVProcessor: | ||
def __init__(self, filename): | ||
self.filename = filename | ||
|
||
def read(self): | ||
with open(self.filename, encoding="utf-8", newline="") as file: | ||
return list(csv.DictReader(file)) | ||
|
||
def write(self, data): | ||
with open( | ||
self.filename, mode="w", encoding="utf-8", newline="" | ||
) as file: | ||
writer = csv.DictWriter(file, fieldnames=data[0].keys()) | ||
writer.writeheader() | ||
writer.writerows(data) | ||
|
||
|
||
class JSONProcessor: | ||
def __init__(self, filename): | ||
self.filename = filename | ||
|
||
def read(self): | ||
with open(self.filename, encoding="utf-8") as file: | ||
return json.load(file) | ||
|
||
def write(self, data): | ||
with open(self.filename, mode="w", encoding="utf-8") as file: | ||
json.dump(data, file, indent=2) | ||
|
||
|
||
class FileProcessor: | ||
def __init__(self, filename, processor): | ||
self.filename = filename | ||
self.processor = processor(filename) | ||
|
||
def __getattr__(self, attr): | ||
return getattr(self.processor, attr) | ||
|
||
|
||
file_proc = FileProcessor("products.csv", CSVProcessor) | ||
print(file_proc.read()) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
product,price,sold_units | ||
Laptop,1200,30 | ||
Phone,700,50 | ||
Tablet,450,100 | ||
Desktop,1000,20 | ||
Monitor,300,50 |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
def progress(percent=0, width=30): | ||
end = "" | ||
if percent == 100: | ||
end = "\n" | ||
left = width * percent // 100 | ||
right = width - left | ||
print( | ||
"\r[", | ||
"#" * left, | ||
" " * right, | ||
"]", | ||
f" {percent:.0f}%", | ||
sep="", | ||
end=end, | ||
flush=True, | ||
) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
def read_user_input(): | ||
print("Enter word (type 'done' to finish):") | ||
for word in iter(input, "done"): | ||
print(f"Processing word: '{word}'") | ||
|
||
|
||
read_user_input() |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
class Rectangle: | ||
def __init__(self, length, width): | ||
self.length = length | ||
self.width = width | ||
|
||
def area(self): | ||
return self.length * self.width | ||
|
||
def perimeter(self): | ||
return 2 * (self.length + self.width) | ||
|
||
|
||
class Square(Rectangle): | ||
def __init__(self, length): | ||
super().__init__(length, length) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
class Stack: | ||
def __init__(self, items=None): | ||
self.items = list(items) if items is not None else [] | ||
|
||
def push(self, item): | ||
self.items.append(item) | ||
|
||
def pop(self): | ||
return self.items.pop() | ||
|
||
def __bool__(self): | ||
return bool(self.items) |
Oops, something went wrong.