Python Flashcards

(53 cards)

1
Q

What are the logical operators in Python

A

and, or, and not

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

What are the bitwise operators in Python

A

&, |, and ^

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

What are the priorities of the sequence operations in Python

A

x in s, x not in s
s + t, s * n or n * s
s[i], s[i:j], s[i:j:k]
len(s)
min(s)
max(s)
s.index(x[, i[, j]])
s.count(x)

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

What sequence operation is used to test if an item exists in a sequence

A

x in seq True if x exists in seq, False otherwise
x not in seq False if x exists in seq, True otherwise

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

What sequence operation is used to concatenate two sequences

A

seq1 + seq2

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

What sequence operation is used to repeat a sequence

A

seq * n or n*seq

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

What sequence operation is used to return an element or slice of a sequence

A

seq[i] return the ith element
seq[i:j] slice from i to j, not including j
seq[i:j:k] slice from i to j, not including j, with step k

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

What sequence operation is used to get the length of a sequence

A

len(seq) the length of seq

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

What sequence operation is used to get the minimum value of a sequence

A

min(seq) the smallest item of seq

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

What sequence operation is used to get the maximum value of a sequence

A

max(seq) the largest item of seq

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

What sequence operation returns the index of an object in a sequence

A

seq.index(x[,i[, j]]) index of the first occurrence of x (at or after index i and before index j)

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

What sequence operation is counts the number of occurrences of an object in a sequence

A

seq.count(x) total number of occurrences of x in seq

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

What are the basic sequence types in Python

A

list, tuple, range, str, bytes, and bytearray

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

What are Falsey values in Python

A

Constants defined to be false: None and False
Numeric types that are zero: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
Empty sequences and collections: '', (), [], {}, set(), range(0)

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

What are Truthy values in Python

A

Constants defined to be true: True
Numeric types that are not zero
Non-empty sequences or collections

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

What data types are valid keys for a hash map/dictionary

A

Objects: Integer, Float, String, Boolean
Immutable sequences: String, Tuple, Range, Frozenset

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

For small inputs, an array can be faster than a hash map. Why?

A

There is overhead associated with a hash map such as the hash function

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

When designing a hash map what are some good design choices

A
  1. Use a prime number in your hash function which helps spread the keys more evenly
  2. Design a hash function that spreads hashes evenly to avoid collisions
  3. Implement a method to handle collisions: chaining or open addressing
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How can you use a list to simulate a stack

A
stack = []
stack.append(3) # push
stack.pop() # pop
len(stack) # num of element
stack[-1] # peek
if not stack # check empty
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How can you simulate a queue

A
# Initialize a queue
from collections import deque
queue = deque()
queue = deque([1,2,3])

queue.append(4) # Enqueue
queue.pop()     # deque
queue[0]        # peek
len(queue)      # get size
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What built-in function returns the absolute value of a number

A

abs(x)

>>> abs(-10)
10
>>> abs(-3.145)
3.145
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What built-in function converts a number to a binary string

A

bin(x)

>>> bin(10)
'0b1010'
>>> format(10,'b')
'1010'
23
Q

What built-in Python function returns the character corresponding to a given Unicode code point (integer)?

A

chr(i)

>>> chr(97)
'a'
>>> chr(ord('a'))
'a'
24
Q

What built-in function takes two (non-complex) numbers as arguments and returns a pair of numbers consisting of their quotient and remainder when using integer division

A

divmod(a, b)

>>> divmod(30,4)
(7, 2)
25
Which built-in Python function returns an iterator that yields pairs of index and value from an iterable?
`enumerate(iterable, start=0)` ``` >>> list(enumerate(['a','b','c'])) [(0, 'a'), (1, 'b'), (2, 'c')] ```
26
What built-in function returns a floating point number from a number or a string
`float(x)` ``` >>> float(1) 1.0 >>> float(" -1.345\n") -1.345 ```
27
What built-in function returns a new frozenset object
`frozenset(iterable=set())` ``` >>> frozenset([1,2,2,3,4,5,5]) frozenset({1, 2, 3, 4, 5}) ```
28
What built-in function returns the hash value of an object
`hash(object)` ``` >>> hash('foo') 9059890961789401645 >>> hash(1) 1 >>> hash(2) 2 >>> hash(True) 1 >>> hash(False) 0 >>> hash((1,2,5)) 2143910794424799510 ```
29
What built-in function returns the hexadecimal string of an integer
`hex(x)` ``` >>> hex(420) '0x1a4' >>> format(420, 'x') '1a4' >>> format(420, 'X') '1A4' ```
30
What built-in function returns an integer object from a number or a string
`int(number=0)` `int(string, base=10)` ``` >>> int("1234") 1234 >>> int(123.45) 123 >>> int("1234") 1234 >>> int(' -12_345\n') -12345 >>> int('0x1a4', 0) 420 >>> int('0b110100100', 0) 420 >>> int('110100100', 2) 420 ```
31
What built-in function returns the length (number of items) in an object
`len(s)`
32
What built-in function returns a new list object from an iterable
`list(iterable)`
33
Which built-in Python function returns a map object that applies a function to items from one or more iterables?
`map()` **Explanation:** If multiple iterables are provided, the function must accept the same number of arguments. The function is applied to elements from each iterable in parallel. **Example:** ``` >>> list(map(lambda x: x * 2, [1, 2, 3])) [2, 4, 6] >>> list(map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])) [5, 7, 9] ```
34
What built-in function returns the largest item in an iterable or the largest of two or more arguments
**Answer** `max()` **Signature** ``` max(iterable, *, key=None) max(iterable, *, default, key=None) max(arg1, arg2, *args, key=None) ``` **Example** ``` >>> max([1, 5, 3]) 5 >>> max(10, 20, 7) 20 >>> max(["apple", "banana", "pear"]) 'pear' >>> words = ["apple", "banana", "pear"] >>> max(words, key=len) 'banana' >>> numbers = [-4, 1, 7, -10] >>> max(numbers, key=lambda x: abs(x)) -10 ```
35
What built-in Python function returns the smallest item in an iterable, or the smallest of two or more arguments?
**Answer** `min()` **Function Signatures** ``` min(iterable, *, key=None) min(iterable, *, default, key=None) min(arg1, arg2, *args, key=None) ``` **Example** ``` >>> min([3, 1, 4, 2]) 1 >>> min(10, 5, 7) 5 >>> min(["apple", "banana", "pear"], key=len) 'apple' >>> min([], default=0) 0 ```
36
What built-in Python function converts an integer to an octal string?
**Answer** `oct(x)` **Examples** ``` >>> oct(8) '0o10' >>> >>> oct(-56) '-0o70' >>> format(10, 'o') '12' ```
37
What built-in Python function returns an integer representing a Unicode character?
**Answer** `ord(c)` **Example** ``` >>> ord('a') 97 ```
38
What built-in Python function returns a number raised to a power, optionally modulo a third argument?
**Answer** `pow(base, exp, mod=None)` **Examples** ``` >>> pow(2, 4) 16 >>> 2**4 16 ```
39
What built-in Python function creates a range of numbers as a `range` object?
**Answer** `range()` **Signatures** ``` range(stop) range(start, stop, step=1) ``` **Examples** ``` >>> range(5) range(0, 5) >>> list(range(1, 10, 2)) [1, 3, 5, 7, 9] ```
40
What built-in function reverses an sequence
`reversed(seq)` `seq` must implement the `__reversed__()` method
41
What built-in function returns a new set object from an iterable
`set(iterable)`
42
What built-in function returns a slice of an object
`slice(stop)` `slice(start, stop, step=None)` Slice objects are also generated when extend indexing syntax is being used, e.g. `a[start:stop:step]`
43
What built-in function returns a new sorted list from an iterable
`sorted(iterable, /, *, key=None, reverse=False)`
44
What built-in function returns a string version of an object
`str(object='')` `str(object=b'', encoding='utf-8', errors='strict')`
45
What built-in function returns sum of an iterable
`sum(iterable)` `sum(iterable /, start =0)`
46
What built-in function returns a new tuple object from an iterable
`tuple(iterable)`
47
What built-in function is used to iterate over several iterables in parallel
`zip(*iterables, strict=False)` ``` >>> for item in zip([1,2,3], ['a','b','c']): ... print(item) ... (1, 'a') (2, 'b') (3, 'c') ```
48
What are naming conventions for variables and functions
Names should be lowercase separated by underscores (snake case) ``` def add_two_numbers(num_one, num_two): return num_one + num_two ```
49
What are naming conventions for constants
Constants are written in all capital letters with underscores separating words ``` PI = 3.14 MAX_OVERFLOW = 4 TOTAL = 1337 ```
50
How can you simulate a heap
``` from heapq import * heap = [] # add elements to a heap heappush(heap, 2) heappush(heap, 1) heappush(heap, 3) # Check minimum element heap[0] # Pop minimum element heappop(heap) # Get the size of the heap len(heap) # Convert an array to a heap in O(n) nums = [42, 2, 13, 74, 420] heapify(nums) ```
51
How can you count the number of a certain characters in binary, hex, or octal. E.g. Count the number of 1's in `0b101`
``` >>> bin(5) '0b101' >>> bin(5).count('1') 2 >>> hex(54) '0x36' >>> hex(54).count('3') 1 ```
52
What methods are used in string and binary sequence types to determine if the value is a digit, alphabetical, or alphanumeric
`.isdigit()` `.isalpha()` `.isalnum()`
53
What built in module is useful for creating iterators for efficient looping
`itertools` ``` from itertools import * >>> product('ABCD', repeat=2) AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD >>> permutations('ABCD', 2) AB AC AD BA BC BD CA CB CD DA DB DC >>> combinations('ABCD', 2) AB AC AD BC BD CD >>> combinations_with_replacement('ABCD', 2) AA AB AC AD BB BC BD CC CD DD ```