Python Flashcards

1
Q

Filter a list

l = [“ab”, “a”, “c”]
Return items that have a length more than 1

A

list(filter(lambda x: len(x) > 1, l))

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

Use reduce on a List

A

from functions import reduce

reduce(lambda a, b: a + b, myList)

This will sum up all the numbers left to right.

reduce(lambda a, b: a if a > b else b, myList)

This will return the max value from list

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

Insert 5 into Index 0 in List

A

x = [1,2,3,4]

x.insert(0,5)

or

x[0:0] = 5

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

Get character length away from ‘a’

A

x = ‘f’

ord(x) - ord(‘a’)

Can use to build tuple of 26 letters and add count of letters for an anagram problem (can then compare tuples to see if they match and words are anagrams)

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

Separate word into list of characters

A

word = “hello”
chars = [*word]

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

Deque and Operations

A

from collections import deque

x = deque()
x.append()
x.appendleft()
x.pop()
x.popleft))

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

Create decoder with message and alphabet

A

import string

alpha = string.ascii_lowercase
decorder = dict(zip(msg, alpha))

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

Dictionary comprehension

d = {“a”: 1, “b”: 5, “c”: 10}

Return any key over 2

A

{k:v for k,v in d.items() if v > 2}

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

Check if number is int or float

A

(4/2).is_integer()

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

Sum up all dictionary values

A

sum(d.values())

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

Stack underflow

A

stack = []
stack[-1]

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

Create a list with x number of spots

A

l = [0] * x

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

Filter a list

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

Apply function to elements in list

A

a = [1,2,3,4]
list(map(lambda x: x + 1, a))

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

Apply function to elements in dict

A

d = {“x”: 1, “a”: 2, “c”: 3}
c = list(map(lambda x: x + 1, d.values()))
new_d = dict(zip(d.keys(), c))

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

What prints out:

nums = [1,2,3,4,5]
for i in range(0, len(nums)):
print(i)

A

0,1,2,3,4

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

What prints out:

nums = [1,2,3,4,5]
for i in range(0, len(nums) + 1):
print(i)

A

0,1,2,3,4,5

18
Q

Set starting value of a number without using 0

A

x = float(“-inf”)

19
Q

Create dict that won’t throw error when accessing key doesn’t exist

A

from collections import defaultdict

result = defaultdict(list)

20
Q

Scope

A

Block of code where object remains relevant

local / global

21
Q

*args vs **kwargs

A

*args = unnamed args passed a tuple

def func1(this, *args):
print(this)
print(args)

func1(1,2,3)
> 1, (2, 3)

**kwargs = keyword args passed as dict

def func2(**kwargs):
print(kwargs)

func2(this=1, that=2)
> {“this”: 1, “that”: 2)

22
Q

Remove duplicates from a file and write to a second file

A

seen = set()
with open(file1, “r+”) as fromFile, open(file2, “w”) as toFile:
l = fromFile.readlines()
fromFile.seek(0)
fromFile.truncate()
for line in l:
if line in seen:
toFile.write(line)
else:
fromFile.write(line)
seen.add(line)

23
Q

read() vs readline() vs readlines()

A

read(): returns entire file as str
readline(): returns a single line up to line break
readlines(): reads all lines into a list

24
Q

Split a string into a list of lines

A

s = “This list\nThat list”
s.splitlines()

25
Q

Sort list with Lambda

A

l = [“a”, “bb”. “ccc”]
l.sort(key=lambda x: len(x))

26
Q

Delete key from dictionary

A

del d[‘key_name’]

27
Q

Count number of chars in a string with standard library

A

from collections import Counter
x = Counter(“thisthat”)

> > Counter({‘t’: 3, ‘h’: 2, ‘i’: 1, ‘s’: 1, ‘a’: 1})

Can then conver to dict:
dict(x)

28
Q

l.sort() vs sorted(l)

A

l.sort(): Sorts list in-place
sorted(l): Creates new list object that’s sorted

29
Q

Magic methods

A

aka dunder methods

These methods provide a way to define how objects of a class behave in various contexts, such as arithmetic operations, string representations, comparisons, and more

__str__: defines behavior of ‘str(obj)’
__len__: defines behavior of ‘len(obj)’
__add__(self, other): ‘obj1 + obj2’
__eq__(self, other): ‘obj1 == obj2’
__getitem__(self, key): ‘obj[key]’

30
Q

Python dictionary collisions

A

Python uses open addressing to handle dict collisions

31
Q

Memory management

A
  • Memory is managed by a private heap space. Interpreter take scare of heap
  • Built-in garbage collector
32
Q

Inheritance Types

A
  • Single: When a class inherits only one superclass/parent
  • Multiple: When a class inherits multiple superclasses
  • Multilevel: When a class inherits a superclass, then another class inherits from it (parent, child, grandparent)
  • Hierarchical: When one superclass is inherited by multiple derived/child classes
33
Q

Decorators

A

Functions that help add functionality to an existing function without changing the structure of the function.

34
Q

Three Types of Control Flow

A
  1. Break: Terminate loop or statement and pass control to next statement
  2. Continue: Force execution of the next iteration instead of terminating it
  3. Pass: Skip the execution
35
Q

Count number of lines in a file

A

with open(file_path, ‘r’) as f:
line_count = sum(1 for line in f)

or

with open(file_path, ‘r’) as f:
for count, line in enumerate(fp):
pass
print(‘Total Lines’, count + 1)

36
Q

Drop duplicates in a file using Pandas

A

import pandas as pd

df = pd.read_csv(fromFile)
df.drop_duplicates(inplace=True)
df.to_csv(toFile)

37
Q

Use sets to get a list of all words in str1 not in str2 and vice versa

A

words1 = set(str1.split())
words2 = set(str2.split())
result = words1.symmetric_difference(words2)

RETURNS SET

38
Q

Get key with max value from dictionary

A

d = {‘a’: 10, ‘b’: 5, ‘c’: 15, ‘d’: 7}
max(d, key=d.get)

39
Q

Get key with nth largest value

A

d = {‘a’: 10, ‘b’: 5, ‘c’: 15, ‘d’: 7}
l = sorted(d, key=d.get, reverse=True)
l[n]

40
Q

Join two sets together

A

a = set()
b = set()
a.union(b)

41
Q

pass vs continue

A

continue will exit the iteration of the loop. pass will keep going