Python Snippets for Coding Interviews
Strings#
Reverse a String#
str = "Hello"
reversed_str = str[::-1]
print(reversed_str) # Output: "olleH"
Check if a String is a Palindrome#
def is_palindrome(s: str) -> bool:
return s == s[::-1]
s = "racecar"
print(is_palindrome(s)) # Output: True
Sort String#
s = "hello"
sorted_s = ''.join(sorted(s))
print(sorted_s) # Output: "ehllo"
Count Characters in a String#
from collections import Counter
s = "hello"
char_count = Counter(s)
print(char_count) # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Check is String a Number#
a = "10"
print(a.isnumeric()) # True
b = "hi"
print(b.isnumeric()) # False
Conversions#
From String to Number#
s = "10"
num = int(s)
print(num) # Output: 10
From Number to String#
num = 10
s = str(num)
print(s) # Output: "10"
Ascii values: ord, chr#
# Convert character to ASCII value
char = 'A'
ascii_val = ord(char)
print(ascii_val) # Output: 65
# Convert ASCII value to character
ascii_val = 65
char = chr(ascii_val)
print(char) # Output: "A"
Capitalize String#
s = "hello"
capitalized_s = s.capitalize()
print(capitalized_s) # Output: "Hello"
Lists#
Reverse a List#
arr = [1, 2, 3, 4]
reversed_arr = arr[::-1]
print(reversed_arr) # Output: [4, 3, 2, 1]
Sort List#
arr = [3, 1, 4, 1, 5, 9, 2]
sorted_arr = sorted(arr)
print(sorted_arr) # Output: [1, 1, 2, 3, 4, 5, 9]
Count Elements in a List#
arr = [1, 2, 1, 3, 2, 1, 4]
element_count = Counter(arr)
print(element_count) # Output: {1: 3, 2: 2, 3: 1, 4: 1}
Iterate over a List#
arr = [1, 2, 3, 4]
for num in arr:
print(num)
List Comprehension#
List comprehension is a concise way to create lists in Python. It is similar to using a loop but more compact.
arr = [1, 2, 3, 4]
squared_arr = [num**2 for num in arr]
print(squared_arr) # Output: [1, 4, 9, 16]
Dictionaries#
Iterate over a Dictionary#
dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dict.items():
print(key, value)
Check if Key Exists in Dictionary#
dict = {'a': 1, 'b': 2, 'c': 3}
key = 'a'
if key in dict:
print(f"{key} exists in the dictionary.")
Get Value for a Key#
dict = {'a': 1, 'b': 2, 'c': 3}
key = 'a'
value = dict.get(key)
print(value) # Output: 1
Sort Dict by Key#
dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict = {k: dict[k] for k in sorted(dict)}
print(sorted_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
Sort Dict by Value#
dict = {'b': 2, 'a': 1, 'c': 3}
sorted_dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
print(sorted_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
Sets#
Check if Element Exists in Set#
s = {1, 2, 3, 4}
element = 3
if element in s:
print(f"{element} exists in the set.")
Add Element to Set#
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}
Matrix#
Init 2d Array#
rows, cols = 3, 4
matrix = [[0 for _ in range(cols)] for _ in range(rows)]
print(matrix)
Print Matrix#
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(row)