From 51cedc5134a2e234d1060031fc64c9d1aa72b882 Mon Sep 17 00:00:00 2001 From: stefandroid Date: Thu, 21 Aug 2025 00:10:47 +0200 Subject: [PATCH] Add Python --- python.md | 164 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 python.md diff --git a/python.md b/python.md new file mode 100644 index 0000000..16d4332 --- /dev/null +++ b/python.md @@ -0,0 +1,164 @@ +## virtualenv + +```shell +virtualenv venv +source venv/bin/activate +deactivate +``` + +## Dictionaries + +* `d.items()` returns an iterable with key-value pairs as tuples +* `d.keys()` returns an iterable with all keys +* `d.values()` returns an iterable with all values +* `dict(sorted(d.items()))` returns a dict sorted by keys +* `dict(sorted(d.items(), key=lambda x: x[1]))` returns a dict sorted by values +* `d.get(key, default=None)` returns the value for a key +* `d.pop(key, default=None)` removes the key and returns the value for key +* `d.popitem()` removes the last item added and returns it as `(key, value)` (LIFO) + +## Flow Control + +* `break`: Terminate the current loop. +* `continue`: Skip the current iteration of a loop and move to the next iteration. +* `pass`: Do nothing. + +## Iterables + +* `i.all()` returns True if all items are True +* `i.any()` returns True if any item is True +* `i.min()` returns smallest item +* `i.max()` returns largest item +* `i.sum()` returns sum of all items +* `reversed(i)` returns the reverse + +```python +sorted(list) +sorted(list, reverse=True) +sorted(string_list, key=str.lower) # Sort by lower case +sorted(string_list, key=int) # Sort by casted integer +``` + +```python +for i, el in enumerate(list): + print(i, el) ## i = index, el = element +``` + +Merge 2+ lists into one list containing tuples of mapped items: + +```python +list(zip(i1, i2, ...)) # length = shorted list + +from itertools import zip_longest +zip_longest(i1, i2, fillvalue="?") # length = longest list, filled with "?" +``` + +## List Comprehension + +```python +[expression for item in iterable if condition] +[expression if condition else other_expression for item in iterable] +``` + +Filter a list with `[x for x in iterable if condition]`. + +## List Misc + +* `list.extend(iterable)` extends the list by appending all items +* `list.insert(i, x)` inserts `x` at position `i` +* `list.remove(x)` removes the first occurrence of `x` +* `list.count(x)` counts the number of `x` +* `list.pop(i)` removes and returns item at position `i` + +## Queue and Stack + +```python +queue = [] +queue.append(item) # Add to end +queue.pop(0) # Remove and return first + +stack = [] +stack.append(item) # Add to end +stack.pop() # Remove and return last +``` + +## Sets + +```python +s = set() +s.add(item) +s.remove(item) +if item in s: ... +``` + +## Substrings + +```python +substring = s[start:end:step] +``` + +Optional args: + +* start: Starting index (**inclusive**). Defaults to 0. +* end: Stopping index (**exclusive**). Defaults to the end. +* step: Defaults to 1. + +`s[::-1]` reverses a string. + +## String Misc + +All string functions return values, no in-place modifications. + +* `s.strip()` removes any leading and trailing whitespaces (also `lstrip()` and `rstrip()`) +* `''.join(sorted(s))` sorts the characters in a string +* `s.zfill(n)` adds 0 to the beginning until the string is `n` char long. +* `s.isdigit()` returns True if all chars in the string are digits +* `s.isalpha()` returns True if all chars in the string are in the alphabet +* `s.startswith(value)` returns True if the string starts with `value` (can be a tuple for multiple checks) +* `s.upper()` / `s.lower()` for case conversion +* `s.replace(old, new, count)` returns string with the first `count` occurences of `old` replaced by `new` +* `list(s)` converts a string into a list of chars +* `s.split(separator, maxsplit)` splits a string (`separator` defaults to any whitespace, optionally stop splitting after `maxsplit` splits) +* `s.rsplit()` splits from the right +* `s.find(value)` returns the index of the first occurrence of `value`, otherwise -1 + +## Class + +```python +class ClassName: + """Class description""" + + def __init__(self, arg1, arg2=None): + """ + Initializes an object + + Args: + [...] + """ + self.arg1 = arg1 + self.arg2 = arg2 + + def __str__(self): + return (f"{self.arg1=}, {self.arg2=}") + + def function_a(self, new_arg2): + self.new_arg2 = new_arg2 + +obj1 = ClassName("asdf") +print(obj1) +``` + +## Tests + +```python +import pytest + +def test_simple(): + assert function_a() == "Hello" + +@pytest.mark.parametrize("input, expected", [ + (input1, "Hello"), (input2, "Hi") +]) +def test_parameter(input, expected): + assert function_b(input) == expected +```