From 880dfe852dd2cabaee4faf3552b00e2d4a2f4b34 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Mon, 3 Jun 2024 20:10:04 +0200 Subject: [PATCH 1/3] Sample code for the article on built-in functions --- python-built-in-functions/README.md | 3 ++ python-built-in-functions/birds.py | 11 ++++++ python-built-in-functions/calculations.py | 16 ++++++++ python-built-in-functions/circle.py | 20 ++++++++++ python-built-in-functions/commands.py | 28 ++++++++++++++ python-built-in-functions/config.json | 5 +++ python-built-in-functions/config.py | 12 ++++++ python-built-in-functions/evaluator.py | 7 ++++ python-built-in-functions/factory.py | 21 +++++++++++ python-built-in-functions/fibonacci.py | 12 ++++++ python-built-in-functions/files.py | 2 + python-built-in-functions/formatting.py | 8 ++++ python-built-in-functions/guess.py | 18 +++++++++ python-built-in-functions/invert.py | 20 ++++++++++ python-built-in-functions/mean.py | 5 +++ python-built-in-functions/menu.py | 9 +++++ python-built-in-functions/person.py | 9 +++++ python-built-in-functions/point.py | 14 +++++++ python-built-in-functions/point_v1.py | 27 ++++++++++++++ python-built-in-functions/point_v2.py | 25 +++++++++++++ python-built-in-functions/powers.py | 13 +++++++ python-built-in-functions/processors.py | 45 +++++++++++++++++++++++ python-built-in-functions/products.csv | 6 +++ python-built-in-functions/progress.py | 16 ++++++++ python-built-in-functions/reader.py | 7 ++++ python-built-in-functions/shapes.py | 15 ++++++++ python-built-in-functions/stack.py | 12 ++++++ python-built-in-functions/uppercase.py | 9 +++++ 28 files changed, 395 insertions(+) create mode 100644 python-built-in-functions/README.md create mode 100644 python-built-in-functions/birds.py create mode 100644 python-built-in-functions/calculations.py create mode 100644 python-built-in-functions/circle.py create mode 100644 python-built-in-functions/commands.py create mode 100644 python-built-in-functions/config.json create mode 100644 python-built-in-functions/config.py create mode 100644 python-built-in-functions/evaluator.py create mode 100644 python-built-in-functions/factory.py create mode 100644 python-built-in-functions/fibonacci.py create mode 100644 python-built-in-functions/files.py create mode 100644 python-built-in-functions/formatting.py create mode 100644 python-built-in-functions/guess.py create mode 100644 python-built-in-functions/invert.py create mode 100644 python-built-in-functions/mean.py create mode 100644 python-built-in-functions/menu.py create mode 100644 python-built-in-functions/person.py create mode 100644 python-built-in-functions/point.py create mode 100644 python-built-in-functions/point_v1.py create mode 100644 python-built-in-functions/point_v2.py create mode 100644 python-built-in-functions/powers.py create mode 100644 python-built-in-functions/processors.py create mode 100644 python-built-in-functions/products.csv create mode 100644 python-built-in-functions/progress.py create mode 100644 python-built-in-functions/reader.py create mode 100644 python-built-in-functions/shapes.py create mode 100644 python-built-in-functions/stack.py create mode 100644 python-built-in-functions/uppercase.py diff --git a/python-built-in-functions/README.md b/python-built-in-functions/README.md new file mode 100644 index 0000000000..6bf952a0df --- /dev/null +++ b/python-built-in-functions/README.md @@ -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/). diff --git a/python-built-in-functions/birds.py b/python-built-in-functions/birds.py new file mode 100644 index 0000000000..40d87865df --- /dev/null +++ b/python-built-in-functions/birds.py @@ -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") diff --git a/python-built-in-functions/calculations.py b/python-built-in-functions/calculations.py new file mode 100644 index 0000000000..a2a2e46e5f --- /dev/null +++ b/python-built-in-functions/calculations.py @@ -0,0 +1,16 @@ +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) + + +add(1, 2) +subtract(3, 2) +multiply(2, 3) +divide(6, 3) diff --git a/python-built-in-functions/circle.py b/python-built-in-functions/circle.py new file mode 100644 index 0000000000..ced4dabcdf --- /dev/null +++ b/python-built-in-functions/circle.py @@ -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) diff --git a/python-built-in-functions/commands.py b/python-built-in-functions/commands.py new file mode 100644 index 0000000000..48f171fc6b --- /dev/null +++ b/python-built-in-functions/commands.py @@ -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)) diff --git a/python-built-in-functions/config.json b/python-built-in-functions/config.json new file mode 100644 index 0000000000..a30d2f4107 --- /dev/null +++ b/python-built-in-functions/config.json @@ -0,0 +1,5 @@ +{ + "DATABASE_URL": "postgres://user:pass@localhost/dbname", + "DEBUG_MODE": true, + "MAX_CONNECTIONS": 10 +} \ No newline at end of file diff --git a/python-built-in-functions/config.py b/python-built-in-functions/config.py new file mode 100644 index 0000000000..28ae455a4b --- /dev/null +++ b/python-built-in-functions/config.py @@ -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()) diff --git a/python-built-in-functions/evaluator.py b/python-built-in-functions/evaluator.py new file mode 100644 index 0000000000..6cc2eeb800 --- /dev/null +++ b/python-built-in-functions/evaluator.py @@ -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 diff --git a/python-built-in-functions/factory.py b/python-built-in-functions/factory.py new file mode 100644 index 0000000000..a19647339b --- /dev/null +++ b/python-built-in-functions/factory.py @@ -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="john@example.com") +table = Product(name="Table", price=200.0, units=5) diff --git a/python-built-in-functions/fibonacci.py b/python-built-in-functions/fibonacci.py new file mode 100644 index 0000000000..c4f674db02 --- /dev/null +++ b/python-built-in-functions/fibonacci.py @@ -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 diff --git a/python-built-in-functions/files.py b/python-built-in-functions/files.py new file mode 100644 index 0000000000..2a2e0a5c8c --- /dev/null +++ b/python-built-in-functions/files.py @@ -0,0 +1,2 @@ +with open("fruits.txt") as file: + print(file.read()) diff --git a/python-built-in-functions/formatting.py b/python-built-in-functions/formatting.py new file mode 100644 index 0000000000..8be856253d --- /dev/null +++ b/python-built-in-functions/formatting.py @@ -0,0 +1,8 @@ +class Formatter: + @staticmethod + def as_currency(value): + return f"${value:,.2f}" + + @staticmethod + def as_percent(value): + return f"{value:.2%}" diff --git a/python-built-in-functions/guess.py b/python-built-in-functions/guess.py new file mode 100644 index 0000000000..6d0cac893e --- /dev/null +++ b/python-built-in-functions/guess.py @@ -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}") diff --git a/python-built-in-functions/invert.py b/python-built-in-functions/invert.py new file mode 100644 index 0000000000..9320b2c726 --- /dev/null +++ b/python-built-in-functions/invert.py @@ -0,0 +1,20 @@ +def invert_case(text): + result = "" + shift = ord("a") - ord("A") + + for char in text: + code_point = ord(char) + if char.islower(): + result += chr(code_point - shift) + elif char.isupper(): + result += chr(code_point + shift) + else: + result += char + + return result + + +# Example usage +example_string = "Hello, World!" +print("Original:", example_string) +print("Inverted Case:", invert_case(example_string)) diff --git a/python-built-in-functions/mean.py b/python-built-in-functions/mean.py new file mode 100644 index 0000000000..f201a5d272 --- /dev/null +++ b/python-built-in-functions/mean.py @@ -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 diff --git a/python-built-in-functions/menu.py b/python-built-in-functions/menu.py new file mode 100644 index 0000000000..7e7ff78f7c --- /dev/null +++ b/python-built-in-functions/menu.py @@ -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) diff --git a/python-built-in-functions/person.py b/python-built-in-functions/person.py new file mode 100644 index 0000000000..908949f854 --- /dev/null +++ b/python-built-in-functions/person.py @@ -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")) diff --git a/python-built-in-functions/point.py b/python-built-in-functions/point.py new file mode 100644 index 0000000000..8163bd89bb --- /dev/null +++ b/python-built-in-functions/point.py @@ -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)), + ) diff --git a/python-built-in-functions/point_v1.py b/python-built-in-functions/point_v1.py new file mode 100644 index 0000000000..06174f2b46 --- /dev/null +++ b/python-built-in-functions/point_v1.py @@ -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 diff --git a/python-built-in-functions/point_v2.py b/python-built-in-functions/point_v2.py new file mode 100644 index 0000000000..d077ae0fba --- /dev/null +++ b/python-built-in-functions/point_v2.py @@ -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 diff --git a/python-built-in-functions/powers.py b/python-built-in-functions/powers.py new file mode 100644 index 0000000000..1519bc3cd7 --- /dev/null +++ b/python-built-in-functions/powers.py @@ -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 +) diff --git a/python-built-in-functions/processors.py b/python-built-in-functions/processors.py new file mode 100644 index 0000000000..5858e2fb64 --- /dev/null +++ b/python-built-in-functions/processors.py @@ -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()) diff --git a/python-built-in-functions/products.csv b/python-built-in-functions/products.csv new file mode 100644 index 0000000000..a0e6ee10d1 --- /dev/null +++ b/python-built-in-functions/products.csv @@ -0,0 +1,6 @@ +product,price,sold_units +Laptop,1200,30 +Phone,700,50 +Tablet,450,100 +Desktop,1000,20 +Monitor,300,50 \ No newline at end of file diff --git a/python-built-in-functions/progress.py b/python-built-in-functions/progress.py new file mode 100644 index 0000000000..58f7a7a672 --- /dev/null +++ b/python-built-in-functions/progress.py @@ -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, + ) diff --git a/python-built-in-functions/reader.py b/python-built-in-functions/reader.py new file mode 100644 index 0000000000..638bf6d887 --- /dev/null +++ b/python-built-in-functions/reader.py @@ -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() diff --git a/python-built-in-functions/shapes.py b/python-built-in-functions/shapes.py new file mode 100644 index 0000000000..2c1c871552 --- /dev/null +++ b/python-built-in-functions/shapes.py @@ -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) diff --git a/python-built-in-functions/stack.py b/python-built-in-functions/stack.py new file mode 100644 index 0000000000..52b42f8a1a --- /dev/null +++ b/python-built-in-functions/stack.py @@ -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) diff --git a/python-built-in-functions/uppercase.py b/python-built-in-functions/uppercase.py new file mode 100644 index 0000000000..b4b8252a76 --- /dev/null +++ b/python-built-in-functions/uppercase.py @@ -0,0 +1,9 @@ +def is_uppercase(text): + for char in text: + if not (65 <= ord(char) <= 90): + return False + return True + + +print(is_uppercase("HELLO")) # True +print(is_uppercase("Hello")) # False From 157a12f3e4f563703776b32c9683c8d26161d954 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Mon, 3 Jun 2024 20:12:51 +0200 Subject: [PATCH 2/3] Fix the linter issues --- python-built-in-functions/calculations.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/python-built-in-functions/calculations.py b/python-built-in-functions/calculations.py index a2a2e46e5f..03694ace8b 100644 --- a/python-built-in-functions/calculations.py +++ b/python-built-in-functions/calculations.py @@ -10,7 +10,8 @@ exec(function) -add(1, 2) -subtract(3, 2) -multiply(2, 3) -divide(6, 3) +# Uncomment the following lines +# print(add(1, 2)) +# print(subtract(3, 2)) +# print(multiply(2, 3)) +# print(divide(6, 3)) From 58ff37971d8eb6c72d269526b9cd417af0b9e6f9 Mon Sep 17 00:00:00 2001 From: Leodanis Pozo Ramos Date: Wed, 12 Jun 2024 17:49:52 +0200 Subject: [PATCH 3/3] TR update, first round --- python-built-in-functions/invert.py | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 python-built-in-functions/invert.py diff --git a/python-built-in-functions/invert.py b/python-built-in-functions/invert.py deleted file mode 100644 index 9320b2c726..0000000000 --- a/python-built-in-functions/invert.py +++ /dev/null @@ -1,20 +0,0 @@ -def invert_case(text): - result = "" - shift = ord("a") - ord("A") - - for char in text: - code_point = ord(char) - if char.islower(): - result += chr(code_point - shift) - elif char.isupper(): - result += chr(code_point + shift) - else: - result += char - - return result - - -# Example usage -example_string = "Hello, World!" -print("Original:", example_string) -print("Inverted Case:", invert_case(example_string))