Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
vlad-bezden / timer.py
Last active November 9, 2022 16:05
Function decorator to calculate function execution time for either sync or async functions
"""Helper module to calculate function execution time."""
import logging
from functools import wraps
from time import perf_counter
from typing import Any, Awaitable, Callable, Coroutine, ParamSpec, TypeVar
FORMAT = "%(asctime)s %(message)s"
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
logger = logging.getLogger(__name__)
@vlad-bezden
vlad-bezden / deep_flatten.py
Created April 11, 2022 17:37
Flatten multi-level nested iterable (list, tuple, ...)
"""Flatten multy-level nested iterable."""
from typing import Any, Iterable
def deep_flatten(data: Iterable[Any]) -> Iterable[float]:
def inner(data):
if isinstance(data, (int, float)):
return [data]
elif not data:
@vlad-bezden
vlad-bezden / .drone.yml
Created March 17, 2022 18:58
Drone.io file for checking python code. It runs all steps/tasks in parallel, and not doing changes, just validate if code follows isort, black, flake8, mypy standards.
kind: pipeline
name: python_code_check
type: kubernetes
steps:
- name: isort
pull: if-not-exists
image: python:3.10-alpine
depends_on: [clone]
commands:
@vlad-bezden
vlad-bezden / custom_enum.py
Created February 15, 2022 10:27
Python Custom Enum. It inherits from str and Enum, so it will return value in the f-string instead of name
from enum import Enum
class Status(str, Enum):
STOPPED = "STOPPED"
RUNNING = "RUNNING"
COMPLETE = "COMPLETE"
status = Status.RUNNING
@vlad-bezden
vlad-bezden / zip_emulator.py
Created February 15, 2022 10:21
Custom Python Zip Implementation
def emulated_zip(*iterables):
lists = [list(iterable) for iterable in iterables]
while all(lists):
yield tuple(current_list.pop(0) for current_list in lists)
numbers = emulated_zip(["one", "two"], [1, 2])
for i in numbers:
print(i)
@vlad-bezden
vlad-bezden / string_joiner.py
Created October 24, 2021 14:48
Content manager for joining strings. Similar to "join" function,
from contextlib import contextmanager
from typing import List, Any, Iterator
class StringJoiner(List[str]):
def __init__(self, sep: str = " ", *args: str) -> None:
super().__init__(*args)
self.sep = sep
@vlad-bezden
vlad-bezden / minimum_change.py
Created October 17, 2021 20:13
Change Making Problem. The minimum number of coins to get a certain amount of money.
from collections import Counter
from fractions import Fraction
penny = Fraction(1, 100)
nickel = Fraction(5, 100)
dime = Fraction(10, 100)
quarter = Fraction(25, 100)
usd = [penny, nickel, dime, quarter]
@vlad-bezden
vlad-bezden / cutting_data_in_buckets.py
Created September 11, 2021 20:58
Cutting numbers into fixed buckets
"""Cutting numbers into fixed buckets
This is a solution for StackOverflow question
https://datascience.stackexchange.com/questions/45118/cutting-numbers-into-fixed-buckets
"""
from bisect import bisect
from random import sample
data = sample(range(10_000), 1_000)
@vlad-bezden
vlad-bezden / caffeines_level_calculator.py
Created August 29, 2021 20:17
Calculate and show caffeine level in body with time.
"""Calculate and show caffeine level in body with time."""
from math import exp
from typing import Iterable
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [24, 12]
# caffeine half life in hours
HALF_LIFE_HOURS = 5
@vlad-bezden
vlad-bezden / Output.md
Last active July 9, 2021 11:05
Multiplication table with formatting and validation

Enter mutliplication table for: 10

   1   2   3   4   5   6   7   8   9  10
   2   4   6   8  10  12  14  16  18  20
   3   6   9  12  15  18  21  24  27  30
   4   8  12  16  20  24  28  32  36  40
   5  10  15  20  25  30  35  40  45  50
   6  12  18  24  30  36  42  48  54  60
 7 14 21 28 35 42 49 56 63 70