Fundamentals Flashcards
(54 cards)
List common functions of the random module.
> import random
- random.random()
- random.randrange(upper_bound)
- random.randrange(lower_bound, upper_bound)
- random.shuffle(xs)
- random.choice(xs)
- random.sample(xs, n)
Name all boolean operators
and, or, not, is, ==
Name all values that evaluate to false in predicates.
- False
- None
- 0 and 0.0
- empty list
- empty set
- empty dict
- empty str
How to test all boolean values in a collection xs?
any(xs) or all(xs)
How to sort a collection xs?
sorted(x)
Parameters for sorted.
sorted(xs, key=function, reverse=True)
How to find the extrema in a collection xs?
max(xs) and min(xs)
How to add indexes to elements of a collection xs?
enumerate(xs)
Demonstrate list comprehensions.
[x * y for x in xs
for y in ys
if x % y == 0]
Demonstrate a dict comprehension.
{k: v for (k, v) in zip(xs, ys)}
Demonstrate a set comprehension.
{x for x in xs}
List the 5 most common built-in collections
- tuple
- list
- set
- dict
- (str)
How to test if an object x is contained in a collection xs?
x in xs
List 4 commonly used non-standard collections.
- defaultdict(factory_function)
- dequeue
- Counter
- OrderedDict
How to get the number of elements in a collection xs?
len(xs)
Get the 3rd up to and including the 9th element of a list xs.
xs[3:10]
Unpack a list (or tuple) literal with 3 elements to:
- three variables a, b and c
- two variables a and b
- > a, b, c = [1, 2, 3]
- > a, *b = [1, 2, 3]
Methods to add and sort list objects.
- extend(another_list)
- add(an_element)
- sort()
Methods to add and remove elements from the set xs.
- xs.add(element)
- xs.discard(element)
- xs.remove(element)
remove raises KeyError if the value not present
Methods to access the contents of a dict xs.
- xs.get(key, default_value)
- xs.keys()
- xs.values()
- xs.items()
In which module can you find the defaultdict and Counter classes?
In the collections module.
How to get the sum of all elements in a collection xs?
sum(xs)
How can you catch exceptions?
try:
x * 3
except NameError as e:
print(‘error: ‘ + str(e))
Demonstrate “if then else”.
if predicate_a:
<some></some>
elif predicate_b:
<some></some>
else:
<some></some>
<variable> = <some> <strong>if</strong> <em>predicate</em> <strong>else</strong> <some></some></some></variable>