Miscellaneous Flashcards

1
Q

What is a generator?

A

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

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

What is the iterator protocol?

A

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.

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

What two methods must an iterator have?

A

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.

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

def fun(n):
for i in range(n):
yield i

How would you use this generator object?

A

You cannot invoke it implicitly you have to iterate through it

for v in fun(5):
print(v)

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

What does the yield keyword do to a function?

A

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.)

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

What is the conditional expression?

A

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.

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

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?

A

One is list comprehension []

two is a generator ()

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

How is the lambda function declared?

A

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()))

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

Why do we use lambdas?

A

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

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

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

A

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)

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

What are the parameters of the map() function?

A

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.

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

example of map and lambda function

A

list_1 = [x for x in range(5)]
list_2 = list(map(lambda x: 2 ** x, list_1))

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

What does the filter function do?

A

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))

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

What is a closure?

A

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

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

What does python use to communicate with files?

A

streams

The operation of connecting the stream with a file is called opening the file, while disconnecting this link is named closing the file.

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

What are the two basic operations performed on the stream?

A

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.

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

What are the two types of streams?

A

text and binary streams

text streams are read line by line
binary streams are read byte by byte

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

What is a portable program?

A

A program that allows executing in different envionrments

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

How do you open a stream?

A

stream = open(file, mode = ‘r’, encoding = None)

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

What does open mode r mean?

A

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.

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

What does open mode w mean?

A

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.

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

What does open mode a mean?

A

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.)

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

What does open mode r+ mean?

A

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.

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

What does open mode w+ mean?

A

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.

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

What does it mean if there is a ‘b’ at the end of the mode string?

A

it means that the stream is to be opened in the binary mode.

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

What does it mean if there is a ‘t’ at the end of the mode string?

A

it means that the stream is to be opened in the text mode.

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

What is the default mode, text or binary?

A

text

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

Opening a file will set the current file position to where in terms of bytes? (examples for a and no a)

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.

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

What does the x open mode do?

A

open a file for its exclusive creation. If the file already exists, the open() function will raise an exception.

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

What three streams are already open when a program starts?

A

import sys

The names of these streams are: sys.stdin, sys.stdout, and sys.stderr.

31
Q

Describe sys.stdin

A

sys.stdin
stdin (as standard input)
the stdin stream is normally associated with the keyboard, pre-open for reading and regarded as the primary data source for the running programs;
the well-known input() function reads data from stdin by default.

32
Q

Describe sys.stdout

A

sys.stdout
stdout (as standard output)
the stdout stream is normally associated with the screen, pre-open for writing, regarded as the primary target for outputting data by the running program;
the well-known print() function outputs the data to the stdout stream.

33
Q

Describe sys.stderr

A

sys.stderr
stderr (as standard error output)
the stderr stream is normally associated with the screen, pre-open for writing, regarded as the primary place where the running program should send information on the errors encountered during its work;
we haven’t presented any method to send the data to this stream (we will do it soon, we promise)
the separation of stdout (useful results produced by the program) from the stderr (error messages, undeniably useful but does not provide results) gives the possibility of redirecting these two types of information to the different targets. More extensive discussion of this issue is beyond the scope of our course. The operation system handbook will provide more information on these issues.

34
Q

What is the last operation performed on the stream?

A

stream.close()

the name of the function is definitely self-commenting: close()
the function expects exactly no arguments; the stream doesn’t need to be opened
the function returns nothing but raises IOError exception in case of error;
most developers believe that the close() function always succeeds and thus there is no need to check if it’s done its task properly.

This belief is only partly justified. If the stream was opened for writing and then a series of write operations were performed, it may happen that the data sent to the stream has not been transferred to the physical device yet (due to mechanism called caching or buffering).

Since the closing of the stream forces the buffers to flush them, it may be that the flushes fail and therefore the close() fails too.

35
Q

Which exception catches stream problems?

A

IOError

attribute errno

36
Q

What does errno.EACCES mean?

A

Permission denied

The error occurs when you try, for example, to open a file with the read only attribute for writing.

37
Q

What does errno.EBADF mean?

A

Bad file number

The error occurs when you try, for example, to operate with an unopened stream.

38
Q

What does errno.EEXIST mean?

A

File exists

The error occurs when you try, for example, to rename a file with its previous name.

39
Q

What does errno.EFBIG mean?

A

File too large

The error occurs when you try to create a file that is larger than the maximum allowed by the operating system.

40
Q

What does errno.EISDIR mean?

A

Is a directory

The error occurs when you try to treat a directory name as the name of an ordinary file.

41
Q

What does errno.EMFILE mean?

A

Too many open files

The error occurs when you try to simultaneously open more streams than acceptable for your operating system.

42
Q

What does errno.ENOENT mean?

A

No such file or directory

The error occurs when you try to access a non-existent file/directory.

43
Q

What does errno.ENOSPC mean?

A

No space left on device

The error occurs when there is no free space on the media.

44
Q

What does strerror() do?

A

Its role is simple: you give an error number and get a string describing the meaning of the error.

45
Q

What are the two python classes used to process files?

A

n general, the BufferedIOBase is able to process any file, while TextIOBase is a specialized class dedicated to processing text files (i.e. files containing human-visible texts divided into lines using new-line markers). Thus, the streams can be divided into binary and text ones

46
Q

What method can you use to read text files?

A

file.read()

47
Q

What method can you use to treat the file as a set of lines not characters?

A

readline()

The method tries to read a complete line of text from the file, and returns it as a string in the case of success. Otherwise, it returns an empty string.

48
Q

What does readlines do ()

A

The readlines() method, when invoked without arguments, tries to read all the file contents, and returns a list of strings, one element per file line.

49
Q

Is an open(‘text.txt’,’rt’) file iterable?

A

yes

The iteration protocol defined for the file object is very simple - its __next__ method just returns the next line read in from the file.

50
Q

How do you write a text file?

A

file.write(‘string’)

The method is named write() and it expects just one argument - a string that will be transferred to an open file (don’t forget - the open mode should reflect the way in which the data is transferred - writing a file opened in read mode won’t succeed)

If you want line you need to add new line character yourself \n

51
Q

What is amorphous data?

A

Amorphous data is data which have no specific shape or form - they are just a series of bytes.

52
Q

What store amorphous data?

A

bytearray - an array containing (amorphous) bytes.

53
Q

What are the two rules of bytearrays?

A

Elements have to be integers (type error if not)

Value has to be from 0 to 255 inclusive (value error if not)

54
Q

What method do you use to read binary files?

A

readinto()
as the method doesn’t create a new byte array object, but fills a previously created one with the values taken from the binary file.

from os import strerror

data = bytearray(10)

try:
bf = open(‘file.bin’, ‘rb’)
bf.readinto(data)
bf.close()

for b in data:
    print(hex(b), end=' ') except IOError as e:
print("I/O error occurred:", strerror(e.errno))
55
Q

How do you use read() with a binary file?

A

data = bytearray(bf.read())

56
Q

What is the argument in the read(arg) meaning?

A

it specifies the maximum number of bytes to be read.

57
Q

What are the four different read methods?

A

read(number) – reads the number characters/bytes from the file and returns them as a string; is able to read the whole file at once;
readline() – reads a single line from the text file;
readlines(number) – reads the number lines from the text file; is able to read all lines at once;
readinto(bytearray) – reads the bytes from the file and fills the bytearray with them;

58
Q

What are the two different ways to use write?

A

write(string) – writes a string to a text file;
write(bytearray) – writes all the bytes of bytearray to a file;

59
Q

What does the os module let you do?

A

Interact with the operating system using python

e.g.
get info about the operating system
manage processes
operate on I/O streams using file descriptions

60
Q

what does os.uname() return?

A

systemname — stores the name of the operating system;
nodename — stores the machine name on the network;
release — stores the operating system release;
version — stores the operating system version;
machine — stores the hardware identifier, e.g., x86_64.

61
Q

What does os.name() return?

A

Prints the name of the operating system

posix — you’ll get this name if you use Unix;
nt — you’ll get this name if you use Windows;
java — you’ll get this name if your code is written in Jython.

62
Q

What does mkdir do?

A

allows you to create a dictionary

63
Q

Whats the difference between my_first_directory
./my_first_directory
../my_first_directory
/python/my_first_director

A

my_first_directory — this is a relative path which will create the my_first_directory directory in the current working directory;
./my_first_directory — this is a relative path that explicitly points to the current working directory. It has the same effect as the path above;
../my_first_directory — this is a relative path that will create the my_first_directory directory in the parent directory of the current working directory;
/python/my_first_directory — this is the absolute path that will create the my_first_directory directory, which in turn is in the python directory in the root directory.

64
Q

What does chmod do?

A

Change directory permissions

65
Q

Can you make a directory if it already exists?

A

No

66
Q

What does the listdir() function do?

A

The listdir function returns a list containing the names of the files and directories that are in the path passed as an argument.

if no argument is passed the current directory will be used

67
Q

What does makedirs() do?

A

The makedirs function enables recursive directory creation, which means that all directories in the path will be created. Let’s look at the code in the editor and see how it is in practice.

os.makedirs(“my_first_directory/my_second_directory”)

second inside first

68
Q

How do you change between directories?

A

chdir()

os.chdir(“my_first_directory”)

69
Q

How do you get info about the current working directory?

A

os.getcwd()

70
Q

How do you delete directories (single and mulitple)?

A

rmdir() - single
removedirs() - multiple

When deleting a directory, make sure it exists and is empty, otherwise an exception will be raised.

To remove a directory and its subdirectories, you can use the removedirs function, which requires you to specify a path containing all directories that should be removed:

71
Q

What does the system function do?

A

os.system(“mkdir my_first_directory”)

command passed within string

establishes connection with CMD

72
Q

a = [1]
b=a[:]
a[0]=0

b?

A

1

73
Q

a = [1]
b=a
a[0]=0

b?

A

0

74
Q

What are two ways are reading binary data?

A

data = open(file,’rb’)
d = bytearray(data.read())

OR

ba = bytearray( number_ofBytes )
data.readinto(ba)