Most Important Python Syntax For Interviews

July 1, 2024

STRINGS

s = 'a1b'
for char in s:
    print(char, char.isalpha())
# shifting
string = "abcdefg"
output = [0]*len(string)
shift = 1
for i in range(len(string)):
    output[i] = chr(ord('a') + (ord(string[i]) + shift - ord('a')) % 26)
print(output)
# a True
# 3 False
# b True
print(chr(65)) # A
print(chr(97)) # a

ARRAYS

str1 = str2 = "abcd"
n = len(str1)
m = len(str2)
# [val for val in file_dict.values() if len(val) > 1] # example of filtering
# can also enumarte dictionary -> ind = {c: i for i, c in enumerate(order)}
table = [ [0 for col in range(m+1)] for row in range(n+1) ]

li = []
li.append(1) 
w = li.pop()  # => 1 and li is now []
print(w)
other_li = [4, 5, 6]
li + other_li  # => [1, 2, 3, 4, 5, 6]
li.extend(other_li)

# swap
li.append(2)
li.append(3) 
li[0], li[1] = li[1], li[0] # 

#insert at the beginning
li.insert(0, 20)

#insert at index 1
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")

#pop the beginning, slow
li.pop(0)
li.pop(4) # remove index 4

len(other_li)

#sort a tuple for example
# def first(a)
#	return a[0]
#
#li.sort(key=first)

DEQUE

from collections import deque
d = deque('ghi') #3 items, g,h,i
d.append('j')                    # add a new entry to the right side
d.appendleft('f')                # add a new entry to the left side
print(d)                         # show the representation of the deque
###deque(['f', 'g', 'h', 'i', 'j'])
d.pop()                          # return and remove the rightmost item, j
d.popleft()                      # return and remove the leftmost item, f
d.clear()

MAPS

empty_dict = {}
filled_dict = {"one": 1, "two": 2, "three": 3}
filled_dict["one"]  # => 1

filled_dict.keys()  # => ["three", "two", "one"]
filled_dict.values()  # => [3, 2, 1]
filled_dict.items()
print("dict items:",filled_dict.items())

"one" in filled_dict  # => True
1 in filled_dict  # => False

# Use "get()" method to avoid the KeyError
filled_dict.get("four")  # => None
filled_dict.get("four", 0)  # => 0 - DEFAULT

from collections import defaultdict
grid = defaultdict(list)

SETS

empty_set = set()
filled_set = {1, 2, 2, 3, 4}  # => {1, 2, 3, 4}
filled_set.add(5)
filled_set.discard(4)

empty_set == filled_set # False
2 in filled_set  # => True
10 in filled_set  # => False

x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}

print(x.intersection(y)) # {"c"}
print(x.intersection(y, z)) # can add more than one to param {"c"} 

print(x.union(y)) # {a,b,c,d,e}

HEAP

import heapq 
# initializing list 
li = [5, 7, 9, 1, 3] 

# using heapify to convert list into heap 
heapq.heapify(li) 
# using heappush() to push elements into heap, pushes 4 
heapq.heappush(li,4) 

# using heappop() to pop smallest element 
print(heapq.heappop(li))

LOOPS

for val in other_li:
    print("other_li value:", val)

for i in (range(len(other_li))):
    print("other_li value using range:", other_li[i])

for idx, val in enumerate(other_li):
  print("other_li - enumerate - index is %d and value is %s" % (idx, val))

for i in range(2): # range(4, 8):
    print("range i:", i)

for value in filled_set:
   print("fillded set val: ", value)

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
   print(f'{name:10} ==> {phone:10d}')
#Sjoerd     ==>       4127
#Jack       ==>       4098
#Dcab       ==>       7678

# print bits 00001 to 11111
N = 5
for i in range(1, 1<< N):
    print("{0:b}".format(i))

CLASSES

class TreeNode:
    def __init__(self, x):
        self.val = x

        self.left = None
        self.right = None
class Search:
    def binarySearch(self, arr, low, high, target):
        if low > high:
            return -1
        
        mid = (low+high) // 2
        current = arr[mid]

        if current == target:
            return mid
        elif current > target:
            return self.binarySearch(arr,low, mid-1, target)
        else: #current < target
            return self.binarySearch(arr, mid+1, high, target)

        return -1

RANDOM

import random
print (random.random())
print (random.uniform(5,10)) #[low, high) 5 to 9

mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, weights = [10, 1, 1], k = 14))

random.random() # Random float:  0.0 <= x < 1.0
random.uniform(2.5, 10.0)# Random float:  2.5 <= x < 10.0
random.expovariate(1 / 5) # Interval between arrivals averaging 5 seconds
random.randrange(10) # Integer from 0 to 9 inclusive
random.randrange(0, 101, 2) # Even integer from 0 to 100 inclusive
random.choice(['win', 'lose', 'draw'])# Single random element from a sequence
deck = 'ace two three four'.split()
random.shuffle(deck) # Shuffle a list
print(deck) #['four', 'two', 'ace', 'three']
random.sample([10, 20, 30, 40, 50], k=4)    # Four samples without replacement

SORTED LIST

# [1, 3, 7, 12] and new number we need to insert is 10, and t = 2. 
# Then we need to consider range [8,12] and check if we have numbers in our SList
# in this range. 
# We can do two binary searches here: 
# bisect_left for left boundary and bisect_right for right boundary. 
# Also we need to check if pos1 != len(SList), if this is the case, 
# it means that new number is bigger than bigges number in list + t, 
# so in this case we just put it directly to our list. 
# If pos1 != pos2, this means, that we found some 
# number i our [nums[i] - t, nums[i] + t] range, so we immediatly return True.
from sortedcontainers import SortedList
class Solution:
    def containsNearbyAlmostDuplicate(self, nums, k, t):
        SList = SortedList()

        for i in range(len(nums)):
            if i > k: 
								SList.remove(nums[i-k-1])   

            pos1 = bisect_left(SList, nums[i] - t)
            pos2 = bisect_right(SList, nums[i] + t)
            
            if pos1 != pos2 and pos1 != len(SList): 
						    return True
            
            SList.add(nums[i])
        
        return False

SortedList(key=lambda x: -x)

sl = SortedList('abcde')
sl.pop()  # 'e'
sl.pop(2) # 'c'
print(sl) # SortedList(['a', 'b', 'd'])

class FreqStack:
    def __init__(self):
        self.history = defaultdict(list)
        self.freq = defaultdict(int)
        self.sortedL = SortedList(key=lambda x: (x[0],x[2]))
        self.time = 0

    def push(self, x: int) -> None:
        self.time += 1       
        oldfreq = self.freq[x]
        
        if oldfreq > 0:
            oldhist = self.history[x][-1]
            self.sortedL.discard((oldfreq, x, oldhist))
                
        self.history[x].append(self.time)
        self.freq[x] += 1        
        
        self.sortedL.add((self.freq[x], x, self.history[x][-1]))        

    def pop(self) -> int:        
        oldfreq, x, oldhist = self.sortedL.pop()
        
        self.freq[x] -= 1
        self.history[x].pop()
        
        if self.freq[x] > 0:
            self.sortedL.add((self.freq[x], x, self.history[x][-1]))
        
        return x
        
        

# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(x)
# param_2 = obj.pop()

ORDERED DICTIONARY

from collections import OrderedDict 
d = OrderedDict() 
d['a'] = 1
d['b'] = 2
d['d'] = 4
d.move_to_end('a')
first = next(iter(d)) # grab first, b
d.pop(first) # {d:4, a:1}

for key, value in d.items(): 
    print(key, value)

ITERTOOLS PERMUTATIONS

import itertools
A = [1,2,3,4]
perms = itertools.permutations(A)
perms = sorted(list(perms), reverse=True)
combos = itertools.combinations(A, 2) # pick 2

LRU CACHE

import functools
@functools.lru_cache(maxsize=None)
def helper(self, s, i, j):        
    n = len(s)
    print(n)
    return 0

GROUPBY

words = ['abc', 'cab', 'cafe', 'goo', 'face']
from itertools import groupby
[list(group) for key,group in groupby(sorted(words,key=sorted),sorted)]
#[['abc', 'cab'], ['cafe', 'face'], ['goo']]

L = [("a", 1), ("a", 2), ("b", 3), ("b", 4)] 
# Key function 
key_func = lambda x: x[0]   
for key, group in groupby(L, key_func): 
    print(key + " :", list(group)) 
#a : [('a', 1), ('a', 2)]
#b : [('b', 3), ('b', 4)]

FILE HANDLING

#https://www.w3schools.com/python/python_file_open.asp
'''
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
'''
f = open("demofile.txt", "r")
print(f.readline())

for x in f:
  print(x)

f.close()