Skip to content

Instantly share code, notes, and snippets.

@brootware
Last active June 22, 2026 04:57
Show Gist options
  • Select an option

  • Save brootware/6570212e73688aff89f3597c4a5505d4 to your computer and use it in GitHub Desktop.

Select an option

Save brootware/6570212e73688aff89f3597c4a5505d4 to your computer and use it in GitHub Desktop.
Cheat Sheet
numlist = [1, 0, 2, 3, 0, 4, 5, 0]
for i in range(0,len(numlist)):
print(f"index: {i}. Value: {numlist[i]}")
# index: 0. Value: 1
# index: 1. Value: 0
# index: 2. Value: 2
# index: 3. Value: 3
# index: 4. Value: 0
# index: 5. Value: 4
# index: 6. Value: 5
# index: 7. Value: 0
# Sort list
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
result = sorted(tuples, key=lambda x: x[1])
return result
def between_markers(text: str, start: str, end: str) -> str:
# your code here
start_index = text.find(start)
end_index = text.find(end)
text = text[start_index+1:end_index]
return text
print("Example:")
print(between_markers("What is >apple<", ">", "<"))
# These "asserts" are used for self-checking
assert between_markers("What is >apple<", ">", "<") == "apple"
assert between_markers("What is [apple]", "[", "]") == "apple"
def changing_direction(elements: list[int]) -> int:
differences = []
dir_change = 0
for i in range(len(elements)-1):
diff = elements[i+1] - elements[i]
if diff != 0: # Filter out zeros, keep both positive AND negative
differences.append(diff)
# Count direction changes (when sign flips between consecutive differences)
for i in range(len(differences)-1):
if differences[i] * differences[i+1] < 0: # opposite signs multiply to negative
dir_change += 1
return dir_change
# Count frequency
text = "hello world"
freq = {}
for char in text:
freq[char] = freq.get(char, 0) + 1
print(freq)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
most_frequent = max(freq, key=freq.get)
print(most_frequent)
# l
# Merge 2 lists into 1 dict
keys = ["name", "age", "city"]
values = ["Bob", 25, "London"]
result = dict(zip(keys, values))
print(result)
# {'name': 'Bob', 'age': 25, 'city': 'London'}
# Merge 2 dicts
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
# Method 1: update() — modifies dict1 in place
dict1.update(dict2)
print(dict1)
# {'a': 1, 'b': 3, 'c': 4}
# Method 2: unpacking — creates a new dictionary
dict1 = {"a": 1, "b": 2}
merged = {**dict1, **dict2}
print(merged)
# {'a': 1, 'b': 3, 'c': 4}
# Method 3: merge operator (Python 3.9+)
dict1 = {"a": 1, "b": 2}
merged = dict1 | dict2
print(merged)
# {'a': 1, 'b': 3, 'c': 4}
pricelist=[
{"name": "bread", "price": 100},
{"name": "wine", "price": 138},
{"name": "meat", "price": 15},
{"name": "water", "price": 1}
]
# sort by highest price. sort dictionary. sort hashtable
price_sorted = sorted(pricelist, key=lambda x: x['price'], reverse=True)
# [
# {'name': 'wine', 'price': 138},
# {'name': 'bread', 'price': 100},
# {'name': 'meat', 'price': 15},
# {'name': 'water', 'price': 1}
# ]
sample_list = [45, 67, 87, 23, 5, 32, 60]
# Your code below
new_list = []
for i in range(len(sample_list)-1, -1, -1):
new_list.append(sample_list[i])
print(new_list)
# Without declaring another list. Saving space
# We only need to loop through half of the list
for i in range(len(sample_list) // 2):
# Swap the element at index i with the element at the opposite end
sample_list[i], sample_list[length - 1 - i] = sample_list[length - 1 - i], sample_list[i]
print(sample_list)
# map(function, iterable, ...)
fruits = ['apple', 'banana', 'cherry']
lengths = map(len, fruits)
print(list(lengths)) # Output: [5, 6, 6]
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
import itertools
# Generate all unique combinations of 2 flavors
sorbet_duos = itertools.combinations(FLAVORS, 2)
for flavor1, flavor2 in sorbet_duos:
print(f"{flavor1}, {flavor2}")
def merge_sorted_lists(list1, list2):
merged = []
i = 0 # Pointer for list1
j = 0 # Pointer for list2
# Loop until one of the lists is fully exhausted
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
# Append any remaining elements left over in either list
# (One of these slices will naturally be empty)
merged.extend(list1[i:])
merged.extend(list2[j:])
return merged
# Example usage:
list_a = [1, 3, 5, 7]
list_b = [2, 4, 6, 8, 9, 10]
print(merge_sorted_lists(list_a, list_b))
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
not_index = s.find('not')
bad_index = s.find('bad')
# Check if both exist AND 'not' comes before 'bad'
if not_index != -1 and bad_index != -1 and bad_index > not_index:
# Slice everything before 'not', add 'good', and slice everything after 'bad'
return s[:not_index] + 'good' + s[bad_index + 3:]
return s
test(not_bad('This movie is not so bad'), 'This movie is good')
test(not_bad('This dinner is not that bad!'), 'This dinner is good!')
test(not_bad('This tea is not hot'), 'This tea is not hot')
test(not_bad("It's bad yet not"), "It's bad yet not")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment