Python 3 Flashcards

1
Q

When you do 7 / 2 what will you get?

A

3.5 – division is always float division.

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

When you do 6 / 2 what will you get?

A

3.0 – division is always float division.

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

What if you wanted 7 divided by 2 to give you 3?

A

You would do 7 // 2 - the // operator gives the floor.

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

What will print(“A”, “B”) give?

A

“A B”, with a space between the params

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

What if you wanted to do print(“A”, “B”) without a space in the output?

A

Use the optional “end” param: print(“A”, “B”, end=””)

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

How do you get command line input?

A

Use the input(prompt) command.
x = input(“name: “)

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

What is argv?

A

argv is the command line parameters. 0 is the script name.

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

What are the three file modes and the modifier?

A

r: Position at beginning
w: Erase whole file and position at 0
a: Position at end
+: Lets you do both reading and writing

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

How do you open a file?

A

f = open(“file.txt”, ‘r’)

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

Once you have a file open, how do you read it? Both full-file and single-line.

A

f.read() is the full file
f.readline() is a single line.

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

How would you do a variable-length argument list?

A

Use *arg.
def foo(num, *args):

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

what are *args and **kwargs?

A

*args makes a list called args of the remaining arguments.
**kwargs makes a dict of the named arguments.

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

What’s the syntax for defining a class, with its constructor?

A

class ClassName(ParentClass):
def __init__(self, param1, param2):

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

If you’re not using inheritance, what class should be the ParentClass?

A

object (lower-case)

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

What’s the first thing your constructor should always do?

A

Call the parent class constructor.
super(ClassName, self).__init__(param1, param2)

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

What is the thing I always forget about classes?

A

Need to use self.variable, and include (self, arg) in method calls.

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

How do you do multiple inheritance?

A

class ClassName(ParentClass1, ParentClass2)

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

Why don’t you want to use multiple inheritance?

A

Because you can instead use composition – create an instance of Class1 and Class2 within your class and use them as objects.

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

What are typehints and how do they work?

A

It’s when you declare your variable types and return types in your method signature.

def foo(bar: str, baz: int) -> float:

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

How do you specify a generic type in a typehint (for list, tuple, dict, etc.)

A

You have to import the collection type from typing, and then put the generic type in [].

from typing import List, Tuple
def foo(bar: List[Tuple[int]])

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

How do you specify the return type as a typehint?

A

Use ->
def foo(bar: int) -> str:

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

What is an inner function?

A

It’s where you define a function as an objct inside another function, usually used for recursion.

def factorial(num: int) -> int:
def inner_factorial(num: int) -> int:
if num == 1:
return 1
return num * inner_factorial(num - 1)
return inner_factorial(num)

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

What is the syntax for a lambda function?

A

lambda x : x < 5

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

What are the three main places you use a lambda function?

A

filter, map, functools.reduce

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

What’s the place I always want to use a lambda function, but shouldn’t?

A

In a list comprehension. If you do [lambda x : x + 5 for x in values] you will get a list of lambda functions.

List comprehension already has an implicit lambda function – you would just do [x + 5 for x in values]

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

What’s the syntax for filter?

A

filter(lambda x : x < 5, [4, 5, 6])

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

What’s the syntax for map?

A

map(lambda x : x + 5, [4, 5, 6])

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

What’s the syntax for reduce?

A

import functools
functools.reduce(lambda x, y: x + y, [4, 5, 6])

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

What’s the main thing I need to remember about the lambda function methods?

A

That you can combine them, e.g.
list(map(lambda x : x + 5,
filter(lambda x : x > 10, [9, 10, 11])
))
returns [16]

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

How does functools.reduce work?

A

It’s a rolling aggregate. At each step you take the new variable and do the operation to combine it with the rolling aggregate. if it’s lambda x, y then x is the rolling aggregate and y is the new value.

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

What’s the syntax for a named tuple?

A

from collections import namedtuple
Point = namedtuple(“Point”, [“x”, “y”])
p = Point(2, 4)
p.x, p.y

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

Is a named tuple mutable?

A

No, but if it has a mutable type as a property, that is mutable.

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

How would you do an AND or OR over a bunch of variables?

A

all()
any()

34
Q

What’s the syntax for all() / any()?

A

It just takes a list (no lambda), so you are usually using a list comprehension.

all([x >= 5 for x in [4, 5, 6]])

35
Q

What does zip do?

A

It takes two iterables and returns an iterator of tuples combining the two.

36
Q

What does zip do if one of the iterables is longer than the other?

A

It truncates after the shortest iterable runs out.

37
Q

What does zip return?

A

It returns an iterator, if you want an array you have to put it in a list comprehension.

38
Q

What’s the syntax for zip?

A

[x for x in zip([4, 5, 6], [7, 8, 9])]

39
Q

How does enumerate work?

A

It gives you the index as well as the value, within a list.

40
Q

What’s the syntax for enumerate?

A

for idx, val in enumerate(values):

41
Q

What’s the key to thinking of slicing?

A

Think of it as creating a range, as an object you work with.

42
Q

What’s the key to thinking of backwards slicing?

A

The indices in the slice are how many places you step forward, where each place is the division between two items. So x[2:-1] is going from

[ x1 x2 | x3 x4 x5 | x6]
2 from the left, one back from the right.

43
Q

What’s the third parameter in a slice?

A

It’s how many steps you take between the start and finish. If it’s negative, you step backwards.

44
Q

Give an example of doing a backwards slice

A

x[4:1:-1]

You wouldn’t do x[1:4:-1], that’s trying to go from 1 to 4 by stepping backwards and just ends up empty.

45
Q

What if you don’t provide a start or finish for a slice?

A

It just goes until the end.
x[4:] is x from 4 to the end.
x[:3] is x from start to 3.
x[:] is all of x.

46
Q

What’s the easiest way to reverse a list?

A

Use slices.
x[::-1]
That’s all of x, stepping from the end to the start.

47
Q

How do you use slices to change a list?

A

The slice is the range, and when you replace it, you are replacing the whole range. What you replace it with can be longer or shorter, doesn’t matter.

48
Q

How do you use slices to insert into a list?

A

x[2:2] = “foo”

This is defining a range from the second division to the second division. So when you insert there, you are just inserting at that second division, squeezing in between the two numbers it divides.

49
Q

What should you try to avoid in general to by “Pythonic”, according to Grady Morgan?

A

You shouldn’t use for loops. Use various lambda functions combined instead. Or in some cases recursion on inner functions.

50
Q

How do you get the ASCII value of a character?

A

ord(‘A’)

51
Q

How do you get the difference in values between two characters, for instance if you wanted to find F=6 from (F - A + 1)?

A

ord(‘F’) - ord(‘A’) + 1
is 6

52
Q

If you have an ASCII value how do you get the character from it?

A

chr(92)

53
Q

How do you break up a string into individual words?

A

words.split(“ “)

if you do “ “.split(words) you’ll just get an empty string.

54
Q

If you’re getting a syntax error and can’t figure it out, it’s usually because…

A

You used python instead of python3 on the command line.

55
Q

How do you combine a list of words into a sentence?

A

” “.join(words)

56
Q

How are lists implemented in Python?

A

They are a dynamic array.

57
Q

What are the big-O times for different list operations in Python?

A

Insertion at the tail is O(1) amortized.

Insertion at an arbitrary location is O(N) because you have to shift elements down. In particular, insertion at the head.

pop() is O(1) because it deletes from the end of the list.
pop(n) or any sort of deletion is O(N).

Random access is O(1).
len(my_list) is O(1).

58
Q

What are the two best ways to copy a list?

A

B = list(A)
B = A[:]

59
Q

What’s the difference between copy and deepcopy()?

A

if A = [P, Q]
A.copy() is a new list with contents [P, Q]
A.deepcopy() is a new list of [P.deepcopy(), B.deepcopy()]

60
Q

How do you sort a list?

A

sorted(A)

61
Q

How do you create an empty set?

A

set()

{} is an empty map

62
Q

What’s the syntax for a list comprehension?

A

[x + 5 for x in [4, 5, 6] if x > 5]

It’s IF, not WHERE.

63
Q

How do you do floor and ceiling?

A

They’re in the math package.

import math
math.floor
math.ceil

64
Q

How do you use infinity?

A

It’s in the math package.

import math
math.inf

65
Q

What does Optional do in Python?

A

It’s a typehint that says that it’s expected that the parameter may be null.

66
Q

What’s the syntax for using Optional?

A

from typing import Optional

def print_list(node: Optional[ListNode])

67
Q

How do you indicate that a method has void return type?

A

-> None

def foo(bar: int) -> None:

68
Q

What’s the class for Linked Lists?

A

Trick question, there isn’t one. You define it yourself:

class ListNode:
def __init__(self, value, next):
self.value = value
self.next = next

there’s no typehint for next because ListNode hasn’t technically been defined yet, so it’s a syntax error.

69
Q

How do you check if a string is a number?

A

val.isnumeric()

Returns True if every character in the string is a number.

70
Q

Does isnumeric work for negative numbers?

A

No, because “-“ is not a number. You have to check the first character in the string to see if it’s - and if so check val[1:].isnumeric()

71
Q

How do you convert a string to a number?

A

int(my_string)
or
float(my_string)

72
Q

Do int/float conversions work for negative numbers?

A

Yes.

73
Q

How do you do a queue?

A

from collections import deque

q = deque()
q.append(3)
q.popleft()
if not q:
print(“empty”)

74
Q

What are the two things that are confusing about the Python implementation of queue?

A

First, the library is called “deque”. The “de” is for double-ended, and then queue is just spelled wrong (missing the last ue).

Second, the method to remove from the tail of the queue is “popleft” which is not intuitive.

75
Q

How do you do a heap?

A

import heapq

h = [5,3,7,2,9]
heapq.heapify(h)
heapq.heappush(10)
heapq.heappop()

76
Q

How do you use a heap to combine multiple sorted lists?

A

heapq.merge(arr1, arr2, etc.)

or if it’s a list of arrays, heapq.merge(*arrs) to unpack the arrays.

This only returns a generator so you have to do list(heapq.merge(…))

77
Q

If you have a list of items, how would you unpack that list to pass every element in it as a parameter to a method?

e.g. I have six numbers, I want to call foo(num1, num2, num3, etc.)

A

foo(*nums)

78
Q

If I want an array, but the function I’m calling only returns a generator, what do I do?

A

list(whatever)

79
Q

How do you do a min-at-top vs. max-at-top heap?

A

heapq is min-at-top by default. To get max-at-top, you need to take the negative of every number. So when you are doing

heapq.heappush(arr, num)

if you want max-at-top you do

heapq.heappush(arr, -num)

and then val = -heapq.heappop(arr) when you extract it.

80
Q
A