Strings
my_string.upper()
my_string.upper(): # Makes string uppercase.
my_string.lower(): # Makes string lowercase.
my_string.isalpha(): # Returns True if string is alphabetic.
my_string.isalnum(): # Returns True if string is alhpanumeric.
# ASCII Value of a string
ord(my_string) Returns the ascii value of a string.
# Reverse a string
my_string[::-1]
# Split a string a list of characters
list(my_string)
# Check if a string contains a substring
"substring" in my_string
# or
my_string.find("substring") # Returns -1 if not found
# Split a string based on a delimiter
my_string.split(" ")
# Replace a substring
my_string.replace("old", "new")
# Get an index of a character
my_string.index("c")
# Sort a string
my_str = "hello"
# Returns a sorted string
sorted_str = ''.join(sorted(my_str))
# Returns a sorted list of characters
sorted_str_list = sorted(my_str)
Lists
# Enumerate
for count, item in enumerate(iterable, start_index):
print(count)
print(item)
# start_index only affects where count starts.
# All items are still iterated over.
# Sort
list.sort(key=func, reverse=True)
# Subtract indices of list 1 from list 2
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
result = [i2 - i1 for i1, i2 in zip(list1, list2)]
# List Slicing
sublist = list[start:stop]
sublist = list[:stop]
sublist = list[start:]
sublist = list[start:stop:step]
sublist = list[::step]
sublist = list[start::step]
sublist = list[:] # Copy of list
sublist = list[-1] # Last
sublist = list[-2] # 2nd to last
sublist = list[-2:] # Last two
sublist = list[:-2] # All but last two
sublist = list[::-1] # Reversed list
# Find min/max in a list
min(list)
max(list)
Dictionaries
# Remove elements
my_dict.clear()
# Try to pop or return a specified default
my_dict.pop(key, default)
# Pop last key item pair
my_dict.popitem()
# Copy elements
other_dict = my_dict.copy()
other_dict = my_dict.fromkeys(keys, value)
# Get elements
my_dict.get(key, default)
my_dict.setdefault(key, default)
my_dict.items()
my_dict.keys()
my_dict.values()
# Update elements
my_dict.update(other_dict)
# Compare two dictionaries
my_dict == other_dict
Sets
# Create
my_set = set()
my_set = {1, 2, 3}
# Set Size
len(my_set)
# Add
my_set.add(item)
# Remove
my_set.remove(item) # Raises KeyError no item
# Discard
my_set.discard(item) # Does not raise KeyError
# Union
set.union(set1, set2, set3)
# Intersection
set.intersection(set1, set2, set3)
# Difference
my_set.difference(set2)
# Is Subset
my_set.issubset(set2)
# Is Superset
my_set.issuperset(set2)
# Is Disjoint
my_set.isdisjoint(set2)
Comprehensions
# List Comprehension
newlist = [x for x in range(10)]
newlist = [x for x in range(10) if x < 5]
newlist = [x.upper() for x in fruits]
newlist = [x if x != "banana" else "orange" for x in fruits]
# Dict Comprehension
newdict = {key: value for vars in iterable}
newdict = {x: x**2 for x in range(10)}
newdict = {x: x**2 for x in range(10) if x%2 == 0}
Quick Data Structures
# Queue
from collections import deque
queue = deque()
queue = deque([1, 2, 3]) # Initialize queue with items
queue.append(item) # Add item to end of queue
queue.appendleft(item) # Add item to front of queue
item = queue.pop() # Remove and return item from end of queue
queue.popleft() # Grab item from front of queue
# Heap (Priority Queue)
import heapq
heap = []
heapq.heappush(heap, item) # Push item onto heap
item = heapq.heappop(heap) # Pop smallest item from heap
item = heap[0] # Smallest item on heap
heapq.heapify(list) # Turn list into heap
# heqapq is a min heap by default,
# but can be used as a max heap by negating values
heap = []
heapq.heappush(heap, -item)
item = -heapq.heappop(heap)
Bisect
import bisect
# Bisect allows for easy binary search of sorted lists
# Here are some things you can do with it
my_list = [1, 3, 3, 5, 7, 9]
# Bisect left, which returns the index of the leftmost
# value that is greater than or equal to x
index = bisect.bisect_left(my_list, 3) # 1
# Bisect, same as bisect_right, which returns the index of the rightmost
# value that is greater than x
index = bisect.bisect(my_list, 3) # 3
# Insort (same as insort_right) and insort_left
# Can insert values into a sorted list. Take optional
# begin and end arguments
bisect.insort(my_list, 4) # [1, 3, 3, 4, 5, 7, 9]
bisect.insort_left(my_list, 3) # [1, 3, 3, 3, 4, 5, 7, 9]
bisect.insort_right(my_list, 5, 0, 3) # [1, 3, 3, 5, 3, 4, 5, 7, 9]
Sort Hacks
# Sort with a lambda function
# Sorts by second index of each item in list
my_list.sort(key=lambda x: x[1])
# Sort with a custom comparator
def comparator(x, y):
if len(x) < len(y):
return -1
elif len(x) > len(y):
return 1
else:
if x < y:
return -1
elif x > y:
return 1
else:
return 0
# Sorts by length, then alphabetically
list.sort(key=cmp_to_key(comparator))
Easy Lookahead with Slicing
s = "hello"
for i in range(len(s)):
print(s[i:i+3])
# Output: "hel" "ell" "llo" "lo" "o"
# Also works on lists
l = [1, 2, 3, 4, 5]
for i in range(len(l)):
print(l[i:i+3])
# Output: [1, 2, 3] [2, 3, 4] [3, 4, 5] [4, 5] [5]
Common Algorithms
# Binary Search
def binary_search(arr, x):
low, high = 0, len(arr) - 1
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return False
# Traverse a Binary Tree (Inorder, or Breadth-First)
def traverse_tree(root):
if root:
traverse_tree(root.left)
print(root.val)
traverse_tree(root.right)
# Traverse a Binary Tree (Preorder, or Depth-First)
def traverse_tree(root):
if root:
print(root.val)
traverse_tree(root.left)
traverse_tree(root.right)
# Traverse a Binary Tree (Postorder)
def traverse_tree(root):
if root:
traverse_tree(root.left)
traverse_tree(root.right)
print(root.val)
Collections
# Get max count using Counter
counts = collections.Counter(nums)
max_count = max(counts.keys(), key=counts.get)
# Defaultdict will create a default value if key doesn't exist
some_map = collections.defaultdict(int)
some_map[0] += 1
Convert Char to ASCII Value
# Convert a-z to 0-25
def char_to_index(c):
return ord(c) - ord('a')
Leave a Reply