Show Menu
Cheatography

python for interview Cheat Sheet by

python cheat sheet for interview

Queues

Priority Queue
from queue import Priori­tyQueue
 
customers = Priori­tyQ­ueue()
 
custom­ers.pu­t((2, "­Har­ry"))
 
while customers:
 
print(­cus­tom­ers.get())

Heaps

import heapq
heapq.h­ea­pif­y(li)
transform array "­li" into min-heap
heapq._­he­api­fy_­max(li)
transform array "­li" into max-heap
heapq.h­ea­ppu­sh(­li,4)
push element in the heap
heapq.h­ea­ppo­p(li)
pop the smallest element
heapq.n­la­rge­st(3, li1)
get the 3 largest numbers
heapq.n­sm­all­est(3, li1)
get the 3 smallest numbers
heapq.n­sm­all­est(3, tuple_­list, key=lambda x: x[1])
if we want 3 smallest tuple_list second dimension

Deque

deque sized
window = deque(­max­len=3)
 

String

Split
string.sp­lit­(" ", 1) //split first occ
Replace
str.re­pla­ce('e', '')
Replace first occurrence
str.re­pla­ce('e', '',1)
Remove symbols from phrase
paragraph = ''.joi­n([­c.l­ower() if c.isal­num() else ' ' for c in paragr­aph])
check array if matches
banned­_words = set(banned)
for word in toCount:
 if word not in banned_words:
 ...

Arrays

array of set capacity
LRUcache = [] * capacity
sort to new
new_list = sorted­(ol­d_list, key=..., revers­e=...)
sort in place
list.s­ort­(ke­y=..., revers­e=...)
sort by len
list.s­ort­(ke­y=len)
sort column
def takeSecond(elem):
 ­ ­ ­return elem[1]
list.sort(key=takeSecond)

sort on objects

 

Dict

create dict
dict = {}
return keys arr
dict.k­eys()
return values arr
dict.v­alues()
order a dict by value
from operator import itemgetter
sorted_keys = sorted­(to­Red­uce.it­ems(), key=it­emg­ett­er(1))
orderdict
from collec­tions import OrderedDict
  d = OrderedDict()
  d.move_to_end('key')
orderdict by value
from collec­tions import OrderedDict
from operator import itemgetter
  OrderedDict(sorted(d.items(), key = itemge­tte­r(1), reverse = True))
put in first position
d.move­_to­_en­d('­key­',l­ast­=False)
compre­hension list val*2
dict_v­ariable = {key:v­alue*2 for (key,v­alue) in dicton­ary.it­ems()}
dict with array as key
dictio­nar­y[t­upl­e(arr)] = val

Classes

initialise
__init­__(­self, var1, var2)
create iterable
__iter­__(­self)

Files

Read file
wfile = open(w­ord­File, ' r')
split line
for line in wfile:
 word = line[:-1]
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter