Python Flashcards
What are the logical operators in Python
and
, or
, and not
What are the bitwise operators in Python
&
, |
, and ^
What are the priorities of the sequence operations in Python
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)
What sequence operation is used to test if an item exists in a sequence
x in seq
True
if x
exists in seq
, False
otherwisex not in seq
False
if x
exists in seq
, True
otherwise
What sequence operation is used to concatenate two sequences
seq1 + seq2
What sequence operation is used to repeat a sequence
seq * n
or n*seq
What sequence operation is used to return an element or slice of a sequence
seq[i]
return the ith element seq[i:j]
slice from i to j, not including jseq[i:j:k]
slice from i to j, not including j, with step k
What sequence operation is used to get the length of a sequence
len(seq)
the length of seq
What sequence operation is used to get the minimum value of a sequence
min(seq)
the smallest item of seq
What sequence operation is used to get the maximum value of a sequence
max(seq)
the largest item of seq
What sequence operation returns the index of an object in a sequence
seq.index(x[,i[, j]])
index of the first occurrence of x (at or after index i and before index j)
What sequence operation is counts the number of occurrences of an object in a sequence
seq.count(x)
total number of occurrences of x
in seq
What are the basic sequence types in Python
list
, tuple
, range
What are Falsey values in Python
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)
What are Truthy values in Python
Constants defined to be true: True
Numeric types that are not zero
Non-empty sequences or collections
What data types are valid keys for a hash map/dictionary
Objects: Integer, Float, String, Boolean
Immutable sequences: String, Tuple, Range, Frozenset
For small inputs, an array can be faster than a hash map. Why?
There is overhead associated with a hash map such as the hash function
When designing a hash map what are some good design choices
- Use a prime number inf your hash function which helps spread the keys more evenly
- Design a hash function that spreads hashes evenly to avoid collisions
- Implement a method to handle collisions: chaining or open addressing
How can you use a list to simulate a stack
stack = [] stack.append(3) # push stack.pop() # pop len(stack) # num of element stack[-1] # peek if not stack # check empty
How can you simulate a queue
# 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
What built-in function returns the absolute value of a number
abs(x)
>>> abs(-10) 10 >>> abs(-3.145) 3.145
What built-in function converts a number to a binary string
bin(x)
>>> bin(10) '0b1010' >>> format(10,'b') '1010'
What built-in function returns the string representing a character whose Unicode code point is the integer i
chr(i)
>>> chr(97) 'a' >>> chr(ord('a')) 'a'
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
divmod(a, b)
>>> divmod(30,4) (7, 2)
What built-in function returns an enumerate object
enumerate(iterable, start=0)
>>> list(enumerate(['a','b','c'])) [(0, 'a'), (1, 'b'), (2, 'c')]
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
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})
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
What built-in function returns the hexadecimal string of an integer
hex(x)
>>> hex(420) '0x1a4' >>> format(420, 'x') '1a4' >>> format(420, 'X') '1A4'
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
What built-in function returns the length (number of items) in an object
len(s)
What built-in function returns a new list object from an iterable
list(iterable)
What built-in function returns a map object from a function and multiple iterables
map(function, iterable, *iterables)
If additional iterables arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.
What built-in function returns the largest item in an iterable or the largest of two or more arguments
max(iterable, *, key=None)
max(iterable, *, default, key=None)
max(arg1, arg2, *args, key=None)
What built-in function returns the smallest item in an iterable or the smallest of two or more arguments
min(iterable, *, key=None)
min(iterable, *, default, key=None)
min(arg1, arg2, *args, key=None)
What built-in function converts an integer to an octal string
oct(x)
>>> oct(8) '0o10' >>> oct(-56) '-0o70' >>> format(10, 'o') '12'
What built-in function returns an integer representing a Unicode character
ord(c)
>>> ord('a') 97
What built-in function returns the base to the power, e.g. 2^4
pow(base, exp, mod=None)
>>> pow(2,4) 16 >>> 2**4 16
What built-in function returns a range object
class range(stop)
class range(start, stop, step=1)
What built-in function reverses an sequence
reversed(seq)
seq
must implement the \_\_reversed\_\_()
method
What built-in function returns a new set object from an iterable
set(iterable)
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]
What built-in function returns a new sorted list from an iterable
sorted(iterable, /, *, key=None, reverse=False)
What built-in function returns a string version of an object
str(object='')
str(object=b'', encoding='utf-8', errors='strict')
What built-in function returns sum of an iterable
sum(iterable)
sum(iterable /, start =0)
What built-in function returns a new tuple object from an iterable
tuple(iterable)
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')
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
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
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)
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
What methods are used in string and binary sequence types to determine if the value is a digit, alphabetical, or alphanumeric
.isdigit()
.isalpha()
.isalnum()
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