Miscellaneous Flashcards
What is a generator?
A Python generator is a piece of specialized code able to produce a series of values, and to control the iteration process. This is why generators are very often called iterators, and although some may find a very subtle distinction between these two, we’ll treat them as one.
range() function is a generator
What is the iterator protocol?
The iterator protocol is a way in which an object should behave to conform to the rules imposed by the context of the for and in statements. An object conforming to the iterator protocol is called an iterator.
What two methods must an iterator have?
An iterator is an object of a class providing at least two methods (not counting the constructor!):
__iter__() is invoked once when the iterator is created and returns the iterator’s object itself;
__next__() is invoked to provide the next iteration’s value and raises the StopIteration exception when the iteration comes to and end.
def fun(n):
for i in range(n):
yield i
How would you use this generator object?
You cannot invoke it implicitly you have to iterate through it
for v in fun(5):
print(v)
What does the yield keyword do to a function?
It turns the function into a generator
It does not break the function like return
All the variables’ values are frozen, and wait for the next invocation, when the execution is resumed (not taken from scratch, like after return).
The yield statement can be used only inside functions. The yield statement suspends function execution and causes the function to return the yield’s argument as a result. Such a function cannot be invoked in a regular way – its only purpose is to be used as a generator (i.e. in a context that requires a series of values, like a for loop.)
What is the conditional expression?
expression_one if condition else expression_two
It’s a conditional expression - a way of selecting one of two different values based on the result of a Boolean expression.
The value it provides is equal to expression_one when the condition is True, and expression_two otherwise.
one = [1 if x % 2 == 0 else 0 for x in range(10)]
two = (1 if x % 2 == 0 else 0 for x in range(10))
What is the difference?
One is list comprehension []
two is a generator ()
How is the lambda function declared?
lambda parameters: expression
e.g.
two = lambda: 2
sqr = lambda x: x * x
pwr = lambda x, y: x ** y
for a in range(-2, 3):
print(sqr(a), end=” “)
print(pwr(a, two()))
Why do we use lambdas?
The most interesting part of using lambdas appears when you can use them in their pure form - as anonymous parts of code intended to evaluate a result.
A lambda function is a tool for creating anonymous functions.
The code has become shorter, clearer, and more legible when using lambdas
def print_function(args, fun):
for x in args:
print(‘f(‘, x,’)=’, fun(x), sep=’’)
def poly(x):
return 2 * x**2 - 4 * x + 2
print_function([x for x in range(-2, 3)], poly)
Change poly into a lambda function
def print_function(args, fun):
for x in args:
print(‘f(‘, x,’)=’, fun(x), sep=’’)
print_function([x for x in range(-2, 3)], lambda x: 2 * x**2 - 4 * x + 2)
What are the parameters of the map() function?
map(function, list)
The above description is extremely simplified, as:
the second map() argument may be any entity that can be iterated (e.g., a tuple, or just a generator)
map() can accept more than two arguments.
The map(fun, list) function creates a copy of a list argument, and applies the fun function to all of its elements, returning a generator that provides the new list content element by element.
example of map and lambda function
list_1 = [x for x in range(5)]
list_2 = list(map(lambda x: 2 ** x, list_1))
What does the filter function do?
The filter(fun, list) function creates a copy of those list elements, which cause the fun function to return True. The function’s result is a generator providing the new list content element by element
data = [randint(-10,10) for x in range(5)]
filtered = list(filter(lambda x: x > 0 and x % 2 == 0, data))
What is a closure?
closure is a technique which allows the storing of values in spite of the fact that the context in which they have been created does not exist anymore.
A closure has to be invoked in exactly the same way in which it has been declared
def make_closure(par):
loc = par
def power(p): return p ** loc return power
def power is the closure
What does python use to communicate with files?
streams
The operation of connecting the stream with a file is called opening the file, while disconnecting this link is named closing the file.
What are the two basic operations performed on the stream?
read from the stream: the portions of the data are retrieved from the file and placed in a memory area managed by the program (e.g., a variable);
write to the stream: the portions of the data from the memory (e.g., a variable) are transferred to the file.
What are the two types of streams?
text and binary streams
text streams are read line by line
binary streams are read byte by byte
What is a portable program?
A program that allows executing in different envionrments
How do you open a stream?
stream = open(file, mode = ‘r’, encoding = None)
What does open mode r mean?
r open mode: read
the stream will be opened in read mode;
the file associated with the stream must exist and has to be readable, otherwise the open() function raises an exception.
What does open mode w mean?
w open mode: write
the stream will be opened in write mode;
the file associated with the stream doesn’t need to exist; if it doesn’t exist it will be created; if it exists, it will be truncated to the length of zero (erased); if the creation isn’t possible (e.g., due to system permissions) the open() function raises an exception.
What does open mode a mean?
a open mode: append
the stream will be opened in append mode;
the file associated with the stream doesn’t need to exist; if it doesn’t exist, it will be created; if it exists the virtual recording head will be set at the end of the file (the previous content of the file remains untouched.)
What does open mode r+ mean?
r+ open mode: read and update
the stream will be opened in read and update mode;
the file associated with the stream must exist and has to be writeable, otherwise the open() function raises an exception;
both read and write operations are allowed for the stream.
What does open mode w+ mean?
w+ open mode: write and update
the stream will be opened in write and update mode;
the file associated with the stream doesn’t need to exist; if it doesn’t exist, it will be created; the previous content of the file remains untouched;
both read and write operations are allowed for the stream.
What does it mean if there is a ‘b’ at the end of the mode string?
it means that the stream is to be opened in the binary mode.
What does it mean if there is a ‘t’ at the end of the mode string?
it means that the stream is to be opened in the text mode.
What is the default mode, text or binary?
text
Opening a file will set the current file position to where in terms of bytes? (examples for a and no a)
successful opening of the file will set the current file position (the virtual reading/writing head) before the first byte of the file if the mode is not a and after the last byte of file if the mode is set to a.
What does the x open mode do?
open a file for its exclusive creation. If the file already exists, the open() function will raise an exception.