Skip to content

Instantly share code, notes, and snippets.

@asyncnull
Last active October 12, 2024 19:05
Show Gist options
  • Select an option

  • Save asyncnull/216ba5ae29106f0838ef6dba8dc7cca3 to your computer and use it in GitHub Desktop.

Select an option

Save asyncnull/216ba5ae29106f0838ef6dba8dc7cca3 to your computer and use it in GitHub Desktop.
Collections

Python Cheatsheet for Coding Questions

Basics

Variables and Data Types

# Integer
x = 5

# Float
y = 3.14

# String
name = "Alice"

# Boolean
is_valid = True

# NoneType (null)
nothing = None

#Multiple Assignments
m,n = 1,False

# Incriment/Decrement
n = n + 1
n -= 1
n ++ #doesnt work

Control Flow

If-Else Statements

if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

Ternary operator

value_if_true if condition else value_if_false

# Ex:
val = l1 if l1 is not None else l2

Loops

For Loop

range([START],[STOP],[STEP_SIZE]) # STOP IS not mutually inclusive

for i in range(5):
    print(i)

While Loop

i = 0
while i < 5:
    print(i)
    i += 1
    if i == 3:
        break

Math

# Classic Divison
print(5/2)
# output 2.5

# floor divison
print(5//2)
# output 2

# Max / Min
float("inf")
float("-inf")

math.floor(3/2)
math.ceilr(3/2)
math.sqrt(3) # 6
math.pow(3,2) # 9

Functions

def greet(name):
    return f"Hello, {name}!"

print(greet("World"))

Lambda Functions

square = lambda x: x ** 2
print(square(5))

Data Structures

Lists / Arrays

# Creating a list
numbers = [1, 2, 3, 4, 5, 6]

# Length of list
len(numbers) # Output: 6

# check if list is empty
if numbers:
  print numbers

# Accessing elements
print(numbers[0])  # Output: 1
print(number.pop()) # output: 6

# Looping array
for i in range(len(numbers)): # using index
for i in numbers: # using elements
for i,n in enumerate(numbers)# index and element
for arr1, arr2 in zip(numbers1, numbers2) # loop through multiple arrays

# Initialie Fixed size array
a = [None] * 10 #initializes all the 10 with None

# Append
numbers.append(7)
# Insert
numbers.insert([INDEX], [VALUE])
numbers.insert(0,-1) # insesrt -1 at index
# Delete
del numbers[0]
# Pop
numbers.pop() # last element
numbers.pop([INDEX]) # Pop at index
# Remove
numbers.remove(3) # remove element by value, Output: value 3 is removed

# Slicing
numbers = [1, 2, 3, 4, 5, 6]
numbers[0:3] # Output: 1,2,3
numbers[:4] # Output: 1,2,3, 4
numbers[2:] # Output: 3,4,5,6
numbers[-2:] # Return Last 2. Output: 5,6
numbers[-1] # last element of array
numbers[::-1] # reverses array elements

# unpacking
a,b = [1, 2]

# Sort
numbers.sort() # array is modified
print(sorted(numbers)) # array is not modified

# Reverse
numbers[::-1] # Slicing
numbers.reverse()
numbers.sort(reverse=True)

# List comprehension
arr = [i for i in range(5)] # output: [0,1,2,3,4]
squares = [x ** 2 for x in range(4)] # output [1, 4, 9]

# 2D Array
arr = [[0]*3 for i in range(3)]

Tuples

# Tuples are Immutable List
# Creating a tuple
coordinates = (10, 20)

# Accessing elements
print(coordinates[0])  # Output: 10

Queue

# Double ended queue by defult

# import
from collections import deque

# Create
queue = deque()

# Adding elements
queue.append(6)
queue.append(7)
queue.append(8)

queue.appendleft(1)

# Accessing elements
queue.popleft() #Output 1
queue.pop() #Output 8

Sets

# Creating a set
unique_numbers = {1, 2, 3, 3, 4}

# Adding elements
unique_numbers.add(5)

# Removing 
unique_numbers.remove(2)
print(unique_numbers) # 1, 3, 4

# Set from list
s = set([1,2,3])

Map / Dictionary

# Creating a dictionary
map = {}
map['a'] = 1

# length of map
len(map)

# Accessing values
print(map["a"])  # Output: 1
# map.get([ITEM], DEFAULT_VALUE).
# 2nd argument is None by Defult
map.get('b', -1) # Output: -1

# Updating values
map["a"] = 26
map.pop('a')

# Delete
del map['a']

# Dictionary Comprehension
map = { i:2*i for i in range(5)} # {(0,0),(1,2),(2,4),(3,6),(4,8)}

# Looping
for key in map: #or 
for key in map.keys():

for val in map.values():

for key, val in map.items():

Strings

# Strings are immutable

s = "Hello, World!"

# String methods
print(s.lower())  # Output: hello, world!
print(s.upper())  # Output: HELLO, WORLD!
print(s.split(", "))  # Output: ['Hello', 'World!']

s.isalnum() # returns True/False if character is alpha numeric

#ASCII Value
# ord() function
print(ord('a'))

# Join strings
<sep>.join(<iterable>) # Join Syntax
str = ['a', 'b', 'c', 'd', 'e', 'f']
print(''.join(str)) # Join with empty delimiter. # Output: "abcdef"
print(' '.join(str)) # Join with space delimiter. # Output: "a b c d e f"

# Split String
<string>.split(sep,maxsplit) # Split syntax
# maxsplit is an optional argument indicating the number of times you'd like to split <string>. maxsplit has a default value of -1, which splits the string on all occurrences of sep.

str = "a b c d e f"
str.split(' ') #output ['a', 'b', 'c', 'd', 'e', 'f']
					

Heaps

# Heaps are implemented using arrays in python
import heapq

# Min Heap
min_heap = []

# push
heapq.heappush(min_heap,3)
heapq.heappush(min_heap,2)
heapq.heappush(min_heap,4)

min_heap[0] # Min is always at index 0. 
			#Output 2. 

# Pop
heapq.heappop(min_heap)

# Max Heap is not available.
# we can multiply by -1 during push and pop

#Build Heap
arr = [1,2,3,4,5]
heapq.heapify(arr)

Classes

class Doc:
    def __init__(self,name): # constructor
        self.name = name
    def sit(self): # Method
        print(f"{self.name} is sitting")

my_dog = Doc("Willie")
print(my_dog.name)

Advanced Concepts

Nested Functions

def outer_function(outer_param):
    def inner_function(inner_param):
        return outer_param + inner_param

    return inner_function

closure_function = outer_function(10)
print(closure_function(5))  # Output: 15

iter(), next()

The iter() function returns an iterator object.
list1 = [1, 2, 3, 4, 5]
lis_iter = iter(list1)

print(str(type(list1))) 	# Output:  <class 'list'>
print(str(type(lis_iter)))	# Output: <class 'list_iterator'>

list_iterator can be accessed with next() calling it multiple times
print(next(lis_iter))

Recursion

Recursion is a method of solving a problem where the solution depends on solving smaller instances of the same problem.

Factorial Example

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # Output: 120

Fibonacci Example

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))  # Output: 55

collections.Counter()

A counter is a container that stores elements as dictionary keys, and their counts are stored as dictionary values.

from collections import Counter
myList = [1,1,2,3,4,5,3,2,3,4,2,1,2,3]
print Counter(myList) # Counter({2: 4, 3: 4, 1: 3, 4: 2, 5: 1})

Conclusion

This guide provides a comprehensive overview of essential Python concepts, data structures, and advanced topics like nested functions and recursion. These fundamentals will help you effectively solve coding questions in Python.

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment