From 962babf11358cea32675d0b2d0131a096fe04209 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Wed, 27 Nov 2024 15:27:24 -0800 Subject: [PATCH 01/17] Update python.md --- python.md | 340 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 234 insertions(+), 106 deletions(-) diff --git a/python.md b/python.md index 9211ebc758..63e8cfc83e 100644 --- a/python.md +++ b/python.md @@ -3,118 +3,143 @@ title: Python category: Python --- -### Tuples (immutable) +### Tuples (Immutable) ```py -tuple = () +t = () # Empty tuple +t = (1, 2, 3) # Tuple with elements +t = (1,) # Single-element tuple (comma is required) + +# Accessing elements +t[0] # First element +t[-1] # Last element + +# Methods +len(t) # Get the length ``` -### Lists (mutable) +### Lists (Mutable) ```py -list = [] -list[i:j] # returns list subset -list[-1] # returns last element -list[:-1] # returns all but the last element -*list # expands all elements in place +lst = [] # Empty list +lst = [1, 2, 3] # List with elements + +# Accessing and slicing +lst[i:j] # Sublist from index i to j-1 +lst[-1] # Last element +lst[:-1] # All but the last element + +# Modifications +lst[i] = value # Set an element +lst.append(value) # Add to the end +lst.insert(i, value) # Insert at position i +lst.extend(other) # Add multiple elements +lst.pop(i=-1) # Remove and return element (default: last) +lst.remove(value) # Remove first occurrence +del lst[i:j] # Delete slice +list1 + list2 # combine two list + +# Useful methods +lst.sort() # In-place sort +sorted(lst) # Sorted copy +lst.reverse() # In-place reverse +list.count(value) # Counts number of elements with the specified value +",".join(lst) # Join elements into a string if all elements are strings +",".join(map(str, lst)) # Join elements into a string +``` -list[i] = val -list[i:j] = otherlist # replace ith to jth-1 elements with otherlist -del list[i:j] +### Dictionaries (Key-Value Pairs) -list.append(item) -list.extend(another_list) -list.insert(index, item) -list.pop() # returns and removes last element from the list -list.pop(i) # returns and removes i-th element from the list -list.remove(i) # removes the first item from the list whose value is i -list1 + list2 # combine two list -set(list) # remove duplicate elements from a list +```py +d = {} # Empty dict +d = {"a": 1, "b": 2} # Initialize with values -list.reverse() # reverses the elements of the list in-place -list.count(item) -sum(list) +# Accessing and modifying +d["key"] # Access value +d.get("key", "default") # Safe access with default +d["key"] = value # Add or update +d.setdefault("key", "default) # If no key, insert with the specified value +del d["key"] # Delete key-value pair +"key" in d # Checks if key in dict -zip(list1, list2) # returns list of tuples with n-th element of both list1 and list2 -list.sort() # sorts in-place, returns None -sorted(list) # returns sorted copy of list -",".join(list) # returns a string with list elements separated by comma +# Iteration +for key, value in d.items(): # Iterate over key-value pairs + print(key, value) -``` +# Useful methods +d.keys() # List of keys +d.values() # List of values +d.items() # List of key-value pairs -### Dict -```py -dict = {} -dict = {'a': 1, 'b': 2} -dict['c'] = 3 -del dict['a'] # Remove key-value pair with key 'c' -dict.keys() -dict.values() -"key" in dict # let's say this returns False, then... -dict["key"] # if "key" not in dict raises KeyError -dict.get("key") # if "key" not in dict returns None -dict.get("key", "optional return value if no key") -dict.setdefault("key", 1) -**dict # expands all k/v pairs in place +# Error cases: +d["key"] # if "key" not in dict raises KeyError +d.get("key") # if "key" not in dict returns None + +** dict # expands all k/v pairs in place ``` ### Set ```py -set = set() -set = {1, 2, 3} -set.add(4) -set.remove(2) +s = set() # Empty set +s = {1, 2, 3} # Set with values +s = set([1, 2, 3, 3] # Convert List into Set + +# Modifications +s.add(4) # Add element +s.remove(2) # Remove element + +# Set operations +s1 | s2 # Union +s1 & s2 # Intersection +s1 - s2 # Difference +s1 ^ s2 # Symmetric difference ``` ### Iteration ```py -for item in ["a", "b", "c"]: -for i in range(4): # 0 to 3 -for i in range(4, 8): # 4 to 7 -for i in range(1, 9, 2): # 1, 3, 5, 7 -for key, val in dict.items(): -for index, item in enumerate(list): +for i in range(4): # 0 to 3 + for +i in range(4, 8): # 4 to 7 +for i in range(1, 9, 2): # 1, 3, 5, 7 from 1 to 9-1 step by 2 + for +item in lst: # List +for key, value in d.items(): # Dict + for +i, value in enumerate(lst): # With index ``` -### [String](https://docs.python.org/2/library/stdtypes.html#string-methods) +### [String Manipulation](https://docs.python.org/2/library/stdtypes.html#string-methods) ```py -str[0:4] -len(str) - -string.replace("-", " ") -",".join(list) -"hi {0}".format('j') -f"hi {name}" # same as "hi {}".format('name') -str.find(",") -str.index(",") # same, but raises IndexError -str.count(",") -str.split(",") - -str.lower() -str.upper() -str.title() - -str.lstrip() -str.rstrip() -str.strip() - -str.islower() - -/* escape characters */ ->>> 'doesn\'t' # use \' to escape the single quote... - "doesn't" ->>> "doesn't" # ...or use double quotes instead - "doesn't" ->>> '"Yes," they said.' - '"Yes," they said.' ->>> "\"Yes,\" they said." - '"Yes," they said.' ->>> '"Isn\'t," they said.' - '"Isn\'t," they said.' +s = "hello world" + +# Basic methods +s.upper() # HELLO WORLD +s.lower() # hello world +s.strip() # Remove leading/trailing spaces +s.lstrip() or s.rstrip() +lst = s.split(" ") # Split by space into list +s.replace("world", "Python") # Replace substring +",".join(["a", "b", "c"]) # Join elements with a separator + +str.count(value) # Count # of values +str.find(value) # Returns first index of value in str, -1 otherwise +str.index(value) # same, but raises IndexError + +str.isalpha() # True if all the chars are alphabet letters(a-z). +str.isdigit() # True if digit(s) + +# Formatting +f"Hello, {name}!" # f-string +"Hello, {}!".format(name) # Same as f-string +"{:.2f}".format(3.14159) # Format float to 2 decimals + +# Escape Characters +print('doesn\'t') # Use \' to escape the single quote +print("doesn't") # Or use double quotes instead ``` ### Casting @@ -130,18 +155,85 @@ str(float) ### Comprehensions ```py -[fn(i) for i in list] # .map -map(fn, list) # .map, returns iterator +# List comprehension +squared = [x ** 2 for x in range(10)] + +# Dictionary comprehension +squared_dict = {x: x ** 2 for x in range(10)} + +# Set comprehension +unique = {x for x in lst if x > 0} + +# Filter and map +filtered = [x for x in lst if x > 0] +transformed = list(map(str, lst)) + +[fn(i) +for i in list] # .map +map(fn, list) # .map, returns iterator + +filter(fn, list) # .filter, returns iterator +[fn(i) for i in list if i > 0] # .filter.map +``` + +### Queues (FIFO) +```py +from collections import deque + +queue = deque() # Initialize +queue.append(1) # Enqueue +print(queue.popleft()) # Dequeue (FIFO) +print(queue.popright()) # LIFO: Remove and return last sampe as pop() +``` + +#### Using queue.Queue (Thread-Safe): +```py +from queue import Queue + +q = Queue() +q.put(1) # Enqueue +print(q.get()) # Dequeue (FIFO) +print(q.qsize()) # Current size +print(q.empty()) # Check if empty +``` + +### Priority Queues +```py +from queue import PriorityQueue + +pq = PriorityQueue() +pq.put((2, "B")) # Insert with priority 2 +pq.put((1, "A")) # Insert with priority 1 +print(pq.get()) # Dequeue (Lowest priority first): (1, "A") + +# Using heapq for Min-Heaps: +import heapq + +min_heap =[] +heapq.heappush(min_heap, 10) +heapq.heappush(min_heap, 5) +print(heapq.heappop(min_heap)) # Removes and returns smallest: 5 +``` + +### Heap +```py +import heapq -filter(fn, list) # .filter, returns iterator -[fn(i) for i in list if i > 0] # .filter.map +heapq.heapify(lst) # Converts a list into a min-heap in-place +heapq.heappush(heap, item) # Adds item to the heap while maintaining heap order +heapq.heappop(heap) # Removes and returns the smallest element in the heap ``` -### Regex + +### Regex (see https://regex101.com) ```py import re +pattern = r"^\d+$" # Matches integers +if re.match(pattern, "123"): + print("It's a number!") + re.match(r'^[aeiou]', str) re.sub(r'^[aeiou]', '?', str) re.sub(r'(xyz)', r'\1', str) @@ -151,38 +243,74 @@ expr.match(...) expr.sub(...) ``` +## Tips & Tricks + +## Type Conversion + +```py +int("42") # String to int +float("3.14") # String to float +str(42) # Int to string +list("abc") # String to list +``` + +## Sorting + +```py +sorted(lst) # Ascending order +sorted(lst, reverse=True) # Descending order +lst.sort(key=lambda x: x[1]) # Custom sort by second element +``` + +## Useful Built-ins +```py +sum(lst) # Sum of elements +max(lst) # Maximum element +min(lst) # Minimum element +zip(lst1, lst2) # Pair elements +all(lst) # True if all elements are true +any(lst) # True if any element is true +``` + ## File manipulation - + ### Reading ```py -file = open("hello.txt", "r") # open in read mode 'r' -file.close() +file = open("hello.txt", "r") # open in read mode 'r' +file.close() + +# Alternative +with open("file.txt", "r") as f: + content = f.read() # Read entire file +lines = f.readlines() # Read all lines as a list ``` ```py -print(file.read()) # read the entire file and set the cursor at the end of file -print file.readline() # Reading one line -file.seek(0, 0) # place the cursor at the beginning of the file +file.read() # read the entire file and set the cursor at the end of file +file.readline() # Reading one line +file.seek(0, 0) # place the cursor at the beginning of the file ``` ### Writing (overwrite) ```py -file = open("hello.txt", "w") # open in write mode 'w' -file.write("Hello World") - -text_lines = ["First line", "Second line", "Last line"] -file.writelines(text_lines) - +file = open("hello.txt", "w") # open in write mode 'w' +file.write("Hello World") +file.writelines(["First line", "Second line", "Last line"]) file.close() + +# Alternative +with open("file.txt", "w") as f: + f.write("Hello, world!") # Overwrite file +f.writelines(["Line1\n", "Line2\n"]) # Write multiple lines ``` ### Writing (append) ```py -file = open("Hello.txt", "a") # open in append mode -file.write("Hello World again") +file = open("Hello.txt", "a") # open in append mode +file.write("Hello World again") file.close() ``` @@ -190,8 +318,8 @@ file.close() ```py with open("welcome.txt", "r") as file: - # 'file' refers directly to "welcome.txt" - data = file.read() +# 'file' refers directly to "welcome.txt" + data = file.read() # It closes the file automatically at the end of scope, no need for `file.close()`. ``` From af532e951025def07f47792b4754bd1564ae3389 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Sat, 30 Nov 2024 17:59:14 -0800 Subject: [PATCH 02/17] Update python.md --- python.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/python.md b/python.md index 63e8cfc83e..774c2c724b 100644 --- a/python.md +++ b/python.md @@ -67,9 +67,9 @@ for key, value in d.items(): # Iterate over key-value pairs print(key, value) # Useful methods -d.keys() # List of keys -d.values() # List of values -d.items() # List of key-value pairs +list(d.keys() ) # List of keys +list(d.values()) # List of values +list(d.items()) # List of key-value pairs # Error cases: From f893ead20e3cc9a7ecfb1e0df38fddb9fa9dd5cd Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Tue, 3 Dec 2024 20:43:24 -0800 Subject: [PATCH 03/17] fix deque --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index 774c2c724b..ebdb807621 100644 --- a/python.md +++ b/python.md @@ -183,7 +183,7 @@ from collections import deque queue = deque() # Initialize queue.append(1) # Enqueue print(queue.popleft()) # Dequeue (FIFO) -print(queue.popright()) # LIFO: Remove and return last sampe as pop() +print(queue.pop()) # LIFO: Remove and return last element ``` #### Using queue.Queue (Thread-Safe): From f92875948de8a16a0add648cd7ac937ac6682b5c Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Sun, 8 Dec 2024 14:51:01 -0800 Subject: [PATCH 04/17] remove duplicate heapq --- python.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/python.md b/python.md index ebdb807621..530dd1673d 100644 --- a/python.md +++ b/python.md @@ -205,14 +205,6 @@ pq = PriorityQueue() pq.put((2, "B")) # Insert with priority 2 pq.put((1, "A")) # Insert with priority 1 print(pq.get()) # Dequeue (Lowest priority first): (1, "A") - -# Using heapq for Min-Heaps: -import heapq - -min_heap =[] -heapq.heappush(min_heap, 10) -heapq.heappush(min_heap, 5) -print(heapq.heappop(min_heap)) # Removes and returns smallest: 5 ``` ### Heap From ae2ff511d99c5fdebe7e1da077ccba7159b48adf Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 18:53:37 -0800 Subject: [PATCH 05/17] Update python.md --- python.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/python.md b/python.md index 530dd1673d..4862160d00 100644 --- a/python.md +++ b/python.md @@ -33,10 +33,11 @@ lst[:-1] # All but the last element lst[i] = value # Set an element lst.append(value) # Add to the end lst.insert(i, value) # Insert at position i -lst.extend(other) # Add multiple elements -lst.pop(i=-1) # Remove and return element (default: last) -lst.remove(value) # Remove first occurrence -del lst[i:j] # Delete slice +```suggestion +lst.extend([1,2,3]) # Extends list with another list +lst.pop() # Remove and return element. Can also accept an index. +lst.remove(value) # Remove first occurrence of value +del lst[i:j] # Delete slice between i and j-1 list1 + list2 # combine two list # Useful methods From a3aa21dce50399046ab12b7d1522ee5a31b3edc8 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 18:54:35 -0800 Subject: [PATCH 06/17] Update python.md --- python.md | 1 + 1 file changed, 1 insertion(+) diff --git a/python.md b/python.md index 4862160d00..29b660e4bc 100644 --- a/python.md +++ b/python.md @@ -44,6 +44,7 @@ list1 + list2 # combine two list lst.sort() # In-place sort sorted(lst) # Sorted copy lst.reverse() # In-place reverse +reversed(lst) # Reversed copy list.count(value) # Counts number of elements with the specified value ",".join(lst) # Join elements into a string if all elements are strings ",".join(map(str, lst)) # Join elements into a string From 139dcc100e4e89f5ca5e3d95730c70f007c93d04 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 18:56:06 -0800 Subject: [PATCH 07/17] Update python.md --- python.md | 1 - 1 file changed, 1 deletion(-) diff --git a/python.md b/python.md index 29b660e4bc..45503b637e 100644 --- a/python.md +++ b/python.md @@ -33,7 +33,6 @@ lst[:-1] # All but the last element lst[i] = value # Set an element lst.append(value) # Add to the end lst.insert(i, value) # Insert at position i -```suggestion lst.extend([1,2,3]) # Extends list with another list lst.pop() # Remove and return element. Can also accept an index. lst.remove(value) # Remove first occurrence of value From 0c739f8792a7b29aab65c804a4407cd80b656185 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 18:57:59 -0800 Subject: [PATCH 08/17] Update python.md --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index 45503b637e..f3830fd2ae 100644 --- a/python.md +++ b/python.md @@ -43,7 +43,7 @@ list1 + list2 # combine two list lst.sort() # In-place sort sorted(lst) # Sorted copy lst.reverse() # In-place reverse -reversed(lst) # Reversed copy +list(reversed(lst)) # Reversed copy list.count(value) # Counts number of elements with the specified value ",".join(lst) # Join elements into a string if all elements are strings ",".join(map(str, lst)) # Join elements into a string From 09b7f79cc21ed05e00c91396429beccdf2397601 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 18:58:50 -0800 Subject: [PATCH 09/17] Update python.md --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index f3830fd2ae..a6250e41a9 100644 --- a/python.md +++ b/python.md @@ -59,7 +59,7 @@ d = {"a": 1, "b": 2} # Initialize with values d["key"] # Access value d.get("key", "default") # Safe access with default d["key"] = value # Add or update -d.setdefault("key", "default) # If no key, insert with the specified value +d.setdefault("key", "default") # If no key, insert with the specified value del d["key"] # Delete key-value pair "key" in d # Checks if key in dict From f49265997ac380f964ff670ac8bb81d524dfbbf3 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:05 -0800 Subject: [PATCH 10/17] Update python.md --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index a6250e41a9..83bcb24efb 100644 --- a/python.md +++ b/python.md @@ -85,7 +85,7 @@ d.get("key") # if "key" not in dict returns None ```py s = set() # Empty set s = {1, 2, 3} # Set with values -s = set([1, 2, 3, 3] # Convert List into Set +s = set([1, 2, 3, 3]) # Convert List into Set # Modifications s.add(4) # Add element From ba8295ce05092242e6c23389219f05bbfdc1b8bc Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:11 -0800 Subject: [PATCH 11/17] Update python.md --- python.md | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/python.md b/python.md index 83bcb24efb..7b210ae425 100644 --- a/python.md +++ b/python.md @@ -102,14 +102,11 @@ s1 ^ s2 # Symmetric difference ```py for i in range(4): # 0 to 3 - for -i in range(4, 8): # 4 to 7 -for i in range(1, 9, 2): # 1, 3, 5, 7 from 1 to 9-1 step by 2 - for -item in lst: # List -for key, value in d.items(): # Dict - for -i, value in enumerate(lst): # With index +for i in range(4, 8): # 4 to 7 +for i in range(1, 9, 2): # 1, 3, 5, 7 from 1 to 8 step by 2 +for item in lst: +for key, value in dict.items(): +for index, value in enumerate(lst): ``` ### [String Manipulation](https://docs.python.org/2/library/stdtypes.html#string-methods) From 2945dc80218c1f75838cad32945afdb7a6eb9eb0 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:17 -0800 Subject: [PATCH 12/17] Update python.md --- python.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python.md b/python.md index 7b210ae425..a80f410c44 100644 --- a/python.md +++ b/python.md @@ -166,8 +166,7 @@ unique = {x for x in lst if x > 0} filtered = [x for x in lst if x > 0] transformed = list(map(str, lst)) -[fn(i) -for i in list] # .map +[fn(i) for i in list] # .map map(fn, list) # .map, returns iterator filter(fn, list) # .filter, returns iterator From ccfbdf97c75cbbb0edb728032aebcea9952957d7 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:22 -0800 Subject: [PATCH 13/17] Update python.md --- python.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/python.md b/python.md index a80f410c44..6aff3594c4 100644 --- a/python.md +++ b/python.md @@ -234,15 +234,6 @@ expr.sub(...) ## Tips & Tricks -## Type Conversion - -```py -int("42") # String to int -float("3.14") # String to float -str(42) # Int to string -list("abc") # String to list -``` - ## Sorting ```py From acd02495ba62aa1836a7ca80a24f8c385bc9d0c1 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:28 -0800 Subject: [PATCH 14/17] Update python.md --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index 6aff3594c4..32ea5d680e 100644 --- a/python.md +++ b/python.md @@ -263,7 +263,7 @@ file.close() # Alternative with open("file.txt", "r") as f: content = f.read() # Read entire file -lines = f.readlines() # Read all lines as a list + lines = f.readlines() # Read all lines as a list ``` ```py From ca64800e97bf5150f74729782dcd9238a7e1ae24 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:32 -0800 Subject: [PATCH 15/17] Update python.md --- python.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python.md b/python.md index 32ea5d680e..9588320001 100644 --- a/python.md +++ b/python.md @@ -258,6 +258,8 @@ any(lst) # True if any element is true ```py file = open("hello.txt", "r") # open in read mode 'r' +content = f.read() # Read entire file +lines = f.readlines() # Read all lines as a list file.close() # Alternative From a8987134361473fd2c66913eb526538da7987b48 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:37 -0800 Subject: [PATCH 16/17] Update python.md --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index 9588320001..0ee8224441 100644 --- a/python.md +++ b/python.md @@ -285,7 +285,7 @@ file.close() # Alternative with open("file.txt", "w") as f: f.write("Hello, world!") # Overwrite file -f.writelines(["Line1\n", "Line2\n"]) # Write multiple lines + f.writelines(["Line1\n", "Line2\n"]) # Write multiple lines ``` ### Writing (append) From 3b1b5c962737fdc72fe881227574c2862df29ec4 Mon Sep 17 00:00:00 2001 From: Nick Korostelev Date: Thu, 12 Dec 2024 19:12:42 -0800 Subject: [PATCH 17/17] Update python.md --- python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.md b/python.md index 0ee8224441..f63d5a31cb 100644 --- a/python.md +++ b/python.md @@ -300,7 +300,7 @@ file.close() ```py with open("welcome.txt", "r") as file: -# 'file' refers directly to "welcome.txt" + # 'file' refers directly to "welcome.txt" data = file.read() # It closes the file automatically at the end of scope, no need for `file.close()`.