Python Basics Flashcards

1
Q

Use only heapush and heappop

A

from heapq import heappush, heappop

heappussh(pq, (x1,x1))
heappoop(pq)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

import collections and use deque

A

from collections import deque

dq. append(4)
dq. appendleft(5)
dq. pop()
dq. popleft()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Subarray ony [2, 3, 4] from

a = [1, 2, 3, 4, 5, 6, 7, 8]

A

a[1:4]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to imported

Sorted list,dictionary, set in python

A

> > > from sortedcontainers import SortedList
sl = SortedList([‘e’, ‘a’, ‘c’, ‘d’, ‘b’])
sl
SortedList([‘a’, ‘b’, ‘c’, ‘d’, ‘e’])

> > > from sortedcontainers import SortedDict
sd = SortedDict({‘c’: 3, ‘a’: 1, ‘b’: 2})
sd
SortedDict({‘a’: 1, ‘b’: 2, ‘c’: 3})

> > > from sortedcontainers import SortedSet
ss = SortedSet(‘abracadabra’)
ss
SortedSet([‘a’, ‘b’, ‘c’, ‘d’, ‘r’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Count all letter in “abaaaaaafadfs” and put in map

A

from collections import Counter

my_str = "Mary had a little lamb"
counter = Counter(my_str)

print counter[‘a’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Elucid algorithm for base conversion

A

num, n, ans = 134, 0, 0

while num > 0:
    bit = num % 2
    ans = ans | (bit << n)
    num = num // 2
    n += 1

print(ans)

Notes: Elucid with the bit on the 0th index

  • take the base and mod to get the lowest bit
  • divide num = num/base
  • go to the next largest bit
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Check if the element is in an array eg.

[ “3”, “5”, “”] check if empty string in array

A

if “” in arr:

pass

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Reverse string or array

A

string1 = string1[::-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Block comment

A

def increase_salary(sal,rating,percentage):
“”” increase salary base on rating and percentage
rating 1 - 2 no increase
rating 3 - 4 increase 5%
rating 4 - 6 increase 10%

"""
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

String is number

String is letter

A

> > > ‘A’.isalpha()
True

> > > > ‘3’.isnumber()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist.

Input: [1,3,4,2,2]
Output: 2

A
ans = 0 
for i in range(32):
    a,b = 0,0
    for num in nums:
        if num &amp; (1 << i) > 0:
            a += 1
for index in range(1,len(nums)):
    if index &amp; (1 << i) > 0: 
        b += 1 

if a > b: 
    ans |= 1 << i

return ans

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

SortedCollection SortedDict

A) add element 
B) update element value 
C) Remove element 
D) Index position based on key
E) pop smallest element 
F) pop largest element
A

sorted_dict = SortedDict()
SortedDict({‘a’: 4, ‘aa’: 4, ‘abb’: 4, ‘abc’: 5, ‘abd’: 2})

A) add
sorted_dict[“abc”] = 1

B) update
sorted_dict[“abc”] = 5

C) delete
del sorted_dict[“abc”]

D) index
sorted_dict.index([“abc”])
==> 3

F)
>>> sl = SortedList('abcde')
>>> sl.pop()
'e'
>>> sl.pop(-1)
'c'
>>> sl
SortedList(['a', 'b', 'd'])
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Deep Copy an array

A

Array copy:

old_list.copy()
old_list[:]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

“12334” or “123ayu456” is a number

A

string = ‘123ayu456’
print(string.isnumeric())
=> False

string = ‘123456’
print( string.isnumeric())
=> True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

datetime_str = ‘09/19/18 13:55:26’ to date time

A

from datetime import datetime

atetime_object = datetime.strptime(datetime_str, “%m/%d/%y %H:%M:%S”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Random

A

random.randrange(a,b)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Union find 1D O(n)*log**(n)
A) what is data structure of pi array
B) what does lookup function return
C) what does union by rank code look like

A

A)
pi = [[-1,0], [-1.1],[-1,2]…..[-1,n]

for i in range(len(nums)):
        index[nums[i]] = i
        pi.append([-1, 1])

B) Lookup will take an index of an element in the array and return the index of parent

    def lookup(self, pi, index):
        currIndex = index
        children = []
    while pi[currIndex][0] != -1:
        currIndex = pi[currIndex][0]
        children.append(currIndex)

    for childIndex in children:
        pi[childIndex][0] = currIndex 

    return currIndex

C)

idx1, idx2 = index[num], index[num+1]
p1, p2 = self.lookup(pi, idx1), self.lookup(pi, idx2)

        if p1 != p2:
            if pi[p1][1] >= pi[p2][1]:
                pi[p1][1] += pi[p2][1]
                pi[p2][0] = p1
            else: 
                pi[p2][1] += pi[p1][1]
                pi[p1][0] = p2
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Given vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘i’, ‘u’]

get infex of “e”

A
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Sort array
arr = [3, 30, 34, 5, 9]
using sorted and a lambda that take 2 arguments

A) what library and function should be used
B) what does -1 vs 1 vs 0 mean

A
# sort array using lambda  
from functools import cmp_to_key
arr = [3, 30, 34, 5, 9]
res1 = sorted(arr, key=cmp_to_key(lambda x, y: -1 if x > y else x < y or 0), reverse=False)
print(res1)
20
Q

Convert bytes to an int

A

int.from_bytes(buffer, byteorder=’big’, signed=False)

21
Q

Given index i , j find the exact middle

- how is

A

mid = i + (j-i)//2

22
Q

SortedCollection SortedDict

A) left most insert pos of new element 
B) right most insert pos of new element 
C) Iterate though the indexes and values
D) get keys 
E) get values 
F) get items in a tuple 
G) get a subsection 
    - three largest element in the set 
   - three smallest elements in set
H) Get first item by index (ie smallest item)
A

A)&raquo_space;> sl = SortedList([10, 11, 12, 13, 14])
»> sl.bisect_left(12)
2

B)&raquo_space;> sl = SortedList([10, 11, 12, 13, 14])
»> sl.bisect_right(12)
3

C)&raquo_space;> sl = SortedList(‘abcdefghij’)
»> it = sl.irange(‘c’, ‘f’)
»> list(it)
[‘c’, ‘d’, ‘e’, ‘f’]

D) list(sorted_dict.keys())
&raquo_space;> [‘a’, ‘aa’, ‘abb’, ‘abd’]

E) list(sorted_dict.values())
»> [4, 4, 4, 2]

F) [(‘a’, 4), (‘aa’, 4), (‘abb’, 4), (‘abd’, 2)]
»> this is opposite of enumerate

G) list(sorted_dict.islice(1,4))
»> [‘aa’, ‘abb’, ‘abd’]

H)
»> sd = SortedDict({‘a’: 1, ‘b’: 2, ‘c’: 3})
»> sd.peekitem()
(‘c’, 3)

23
Q

power

A

import math

2**4 or math.pow(2,4)

24
Q

Enumerate an array

words = [a,b,d,e,g]

A

for i, word1 in enumerate(words):

print(i, “, “, word1)

25
Q

math square root

A

import math

math.sqrt(4)

26
Q

what is answer for “/”.split()

how to remove the any empty spaces

A

str1 = “/”
str2 = “/a/b/c
“/”.split() –> [””,””]

res1 = [”/”] + list(filter(str.split()))
—> []
res2 = [”/”] + list(filter(str2.split())
—–> [”/”,”b”,”c”]

27
Q

casting to int, float, string

A

int(“9”)
float(“232.32”)
str(1323)

28
Q

A) What is a usecase for cmp_to_key
B) How is is used with labmda
C) Can you used a regular function instead of a lambda as parameter to cmp_to_keys

A

A/B) cmp_to_keys is used in a complex sort to wrap a 2 param function its in the functools library

C) A regular function can also be passed into the cmp_to_keys methods

res2 = sorted(arr, key=cmp_to_key(lambda x,y: -1 if x < y else x > y or 0))
print(res2)

29
Q

Sys constants

A

import sys

sys. maxsize-1
- sys.maxsize

30
Q

String is digit

A

For alphabet

|&raquo_space;> ‘A’.isdigit()

31
Q

heapq

A

import heapq

heapq. heapify(self.pool)
heapq. heappush(self.pool, (val, index))
heapq. heappop(self.pool)

32
Q

Python foor loop from 9 to 0 print each char

A

for i in range(9,0,-1):

print(i)

33
Q

Split a linked list in half

A
slow = head 
fast = head

while fast != None and fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next

34
Q

Dijkstra O(log(V) *E) average case O(N^2) worst case

  • with visited set
A
while len(pq) > 0:        
            uw,u = heapq.heappop(pq) 
            if u in visited:
                continue 
        visited.add(u) 

        for v, vw in graph[u]:
            if weights[v] > uw + vw:
                weights[v] = uw + vw 
                heapq.heappush(pq, (weights[v], v))
35
Q
Bellman For algorithm 
A) use case? 
B) edge weight restrictions?
C) Time complexity (V*|E|)
D) Code
A

cost = [sys.maxsize] * n
cost[src] = 0

    for k in range(K):
        for u, v, cost_u_to_v in flights:     
            if cost[u] == sys.maxsize:
                continue;      

            if cost[v] > costt[u] + cost_u_to_v:
                cost[v] =  cost[u] + cost_u_to_v

    return cost[dst] if cost[dst] != sys.maxsize else -1
36
Q
Bellman For algorithm 
A) use cases? 
B) edge weight restrictions?
C) Time complexity V^3
D) Code
A

for i, j, w in edges:
dis[i][j] = dis[j][i] = w
for i in xrange(n):
dis[i][i] = 0

    for k in xrange(n):
        for i in xrange(n):
            for j in xrange(n):
                dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j])
37
Q

Day difference between date-time objs

A

diffInDays = datetime.now() - datetime_object

38
Q

Dijkstra O(N^2)

  • no visited set
A

heapq.heappush(pq,(0, K))

        while len(pq) > 0:        
            uw,u = heapq.heappop(pq) 
        for v, vw in graph[u]:
            if weights[v] > uw + vw:
                weights[v] = uw + vw 
                heapq.heappush(pq, (weights[v], v))
39
Q

A) What is GCD

B) GCD formula

A

The greatest common divisor (also known as greatest common factor, highest common divisor or highest common factor) of a set of numbers is the largest positive integer number that devides all the numbers in the set without remainder.

GCD = (a*b) / LCM(a,b)

40
Q

Strip a string

A

strVar.strip()

41
Q

Split word

word = ‘geeks:for:geeks’

A

print(word.split(‘:’))

42
Q

Simple date-time constructor

A

from datetime import datetime

x = datetime(2020, 5, 17)

43
Q

Open a file and write to a new file

A

with open(“python-mini.jpg”, “rb”) as fr:

    with open("py-cp2.jpg", "wb") as fw:
        chunk_size = 4
        buffer = fr.read(chunk_size)
        print(buffer)
        intval = int.from_bytes(buffer, byteorder='big', signed=False)
        print(intval)
44
Q

Sort an array by: planet name, size asc

myList = [ {“planet”: “earth”, “size”: 3},
{ “planet”: “saturn”, “size”: 3},
{“planet”: “venus”, “size”: 2},
{“planet”: “pluto”, “size”: 1},
{“planet”: “neptune”, “size”: 4}
]

A
planetName = lambda planet: planet["planet"]
planetsize = lambda planet: (planet["size"], planet["planet"])

list1 = sorted(myList, key=planetsize, reverse=False)

print(list1)

45
Q

A) What is LCM
B) code for LCM
- subtracion method
- mod method

A

the least common multiple, lowest common multiple, or smallest common multiple of two integers a and b, usually denoted by lcm(a, b), is the smallest positive integer that is divisible by both a and b

a = 342
b = 46
def lcm(a,b):
    if a == 0 or b == 0:
        return a
    return lcm(b, a%b)

Take smaller number from larger and keep swapping

46
Q

Turn a = [[1,3,4],[5,4,0]] into a tuple and add it to a set

A

a = [[1,3,4], [5,4,0]]
print((tuple(a[0]), tuple(a[1])))
===> ((1, 3, 4), (4, 5, 0))

mySet.add(myTuple)