Python I Flashcards

1
Q

attribute for getting the dimensions of a numpy array (e. g. (3, 4, 2))

A

arr.shape

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

attribute for getting the datatype of a numpy array

A

arr.dtype

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

attribute for getting the number of dimensions of a numpy array

A

arr.ndim

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

attribute for getting the number of all elements of a numpy array

A

arr.size

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

creating an array in numpy

A

np.array(my_list)

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

creating a range in numpy

A

np.arange(start, stop, step)

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

creating ranges of values in numpy

A

np.linspace(start, stop, numberOfElems, endpoint=True/False)

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

get multiple elements of a numpy array (index)

A

one_dim[[3, 4, 6, 15]] (gets elements at index 3, 4, 5, 6 and 15)

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

get the element of the 3rd row and 4th column of a numpy array

A

arr[2, 3] or arr[(2, 3)]

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

get the second row of a multidimensional numpy array

A

arr[1]

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

get the second column of a multidimensional numpy array

A

arr[: , 1]

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

extract the bottom right 2x2 corner of a 3x4 numpy array

A

arr[1:3, 2:4]

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

indexing of numpy arrays is also possible via masks

A

mask = np.array([[True, False, False, True],
[False, True, False, True],
[False, False, True, True]])
print(“two_dim[mask]”)
print(two_dim[mask])

(Returns flat (1D) array of elements where mask = True)

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

only extract even number out of a numpy array

A

mask = (arr % 2) == 0
print(arr[mask])

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

additional information numpy arrays

A

x2 = two_dim[:][2]

This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”

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

additional information numpy arrays

A

x2 = two_dim[:][2]

This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”

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

additional information numpy arrays

A

x2 = two_dim[:][2]

This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”

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

additional information numpy arrays

A

x2 = two_dim[:][2]

This will first create a slice of the array (in this case, this is simply the entire array again) and then access index 2 in that sliced array, which corresponds to “two_dim[2]”

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

set all elements from index 2 to 4 to zero in a numpy array

A

one_dim[2:5] = [0, 0, 0]

or

one_dim[2:5] = 0 (broadcasting)

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

set all entries of a twodimensional numpy array to 0

A

two_dim[:] = 0

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

set the second to third element of the second row of a numpy array to 0

A

two_dim[1, 1:4] = 0

(also subarrays can be broadcasted, e. g.
two_dim[:, 1:3] = [7, 8])

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

When can numpy arrays be reshaped?

A

When the number of elements stays the same.

a = np.arange(24)
a = a.reshape(2, 3, 4)
a = a.reshape(4, 6)
a = a.reshape(6, -1)

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

add an empty dimension

A

a1 = a[:, None, :]
a2 = a[:, np.newaxis, :]

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

Other important numpy functions

A

print(np.append(a, np.array([1, 2, 3])))
print(np.concatenate([a, a, a]))
print(np.repeat(a, repeats=5))
print(np.tile(a, reps=5))

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

important: sum in numpy arrays

A

Sum (similar functions available for: mean, standard deviation, etc.)
arr = np.arange(2 * 3 * 4).reshape((2, 3, 4)) * 3

print(arr.sum(axis=0)) # Sum along first axis/dimension (axis 0 will be “collapsed” -> shape: (3, 4))

print(arr.sum(axis=1)) # Sum along second axis/dimension (axis 1 will be “collapsed” -> shape: (2, 4))

print(arr.sum(axis=2)) # Sum along second axis/dimension (axis 2 will be “collapsed” -> shape: (2, 3))

print(arr.sum(axis=(1, 2))) # Sum along second + third axis (axis 1 + 2 will be “collapsed” -> shape: (2,))

print(arr.sum()) # “Global” sum along all axes/dimensions

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

Get the (flat!) index of the minimum of a numpy array and transform it into an array-shaped index

A

i_min_flat = arr.argmin()

i_min_shape = np.unravel_index(i_min_flat, shape=arr.shape)

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

numpy functions with conditionals

A

print(np.where(arr % 2 == 0, arr, other)) # If condition is True, take from “arr”, else take from “other”

print((arr > 50).all()) # Check if all elements meet the condition

print((arr > 50).any()) # Check if at least one element meets the condition

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

random values in numpy

A

rng = np.random.default_rng(seed=1234)
arr = rng.random((4, 3))
arr = rng.integers(low=1, high=25, size=5)
arr = rng.choice(np.arange(100), size=10, replace=False)

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

sort a numpy array

A

np.sort(arr)

or

arr.sort() - in-place

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

important info for numpy slicing and reshaping

A

Reshaping and slicing does not copy the original array, it only creates another “view” on the data.

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

regex - search for the first occurence of a pattern

A

re.search(pattern, text)

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

regex - find a pattern at the beginning of the string

A

re.match(pattern, text)

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

regex - groups

A

Groups can be used to only search for subpatterns within a search pattern (e. g. “H(all)o, how (are) you?”)

The found patterns can be accessed like this (0 is the whole pattern, 1 is the first group)
match_object.group(1)

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

Getting additional information from regex group match objects

A

match_object.start(1)
match_object.end(1)
match_object.span(1)

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

regex - find all occurences of a pattern

A

re.findall(pattern, text) -> list

(re.finditer does the same, but does it one item at a time and returns a match object)

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

regex - a set of characters to match

A

[…]

e. g. “[cbr]at”

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

regex - specify ranges

A

[…]

e. g. “[0-5]”

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

regex - negate patterns

A

e. g. “[^0-9]”

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

regex - predefined group for digits

A

\d

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

regex - predefined group for non-digits

A

\D

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

regex - predefined group for whitespace characters

A

\s

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

regex - predefined group for non-whitespace characters

A

\S

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

regex - predefined group for word characters

A

\w

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

regex - predefined group for non-word characters

A

\W

44
Q

regex - match any character (except newline)

A

.

e. g. “.m.”

45
Q

regex - search for alternative patterns

A

|

e. g. “[bcr]at|dog”

46
Q

regex - match any number of repetitions (also 0)

A

*

e. g. “([bcr]at|dog)*”

47
Q

regex - match at least one repetition

A

+

e. g. “([bcr]at|dog)+”

48
Q

regex - be not- greedy (not search for as many repetitions as possible)

A

? (suffix)

49
Q

regex - positive lookahead

A

only match if the following is XYZ

”(?=XYZ)”

50
Q

regex - negative lookahead

A

only match if it is not followed by XYZ

”(?!XYZ)”

51
Q

regex - positive lookbehind

A

only match if the preceeding is XYZ

”(?<=XYZ)”

52
Q

regex - negative lookbehind

A

only match if the preceeding is not XYZ

”(?<!XYZ)”

53
Q

call a program with the subprocess module

A

p = subprocess.Popen([“some_program”, “argument1”, “argument2”]) - will not wait for the program to finish

p.wait(timeout=2) - will wait 2 seconds for the program to finish (except subprocess.TimeoutExpired)

54
Q

get the output and errors of a program

A

p = subprocess.Popen([“ping”, “www.jku.at”], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

outs, errs = p.communicate(timeout=15)

55
Q

simple way of calling a program

A

result = subprocess.run([“some_program”, “argument1”, “argument2”])

result.returncode
result.stdout
result.stderr

56
Q

only execute code in the main process

A

if __name__ == “__main__”

57
Q

use multiprocessing

A

from multiprocessing import Pool

arguments = list(range(100))

without dynamic iterable:
with Pool(4) as p:
pool_returns = p.map(fcn, arguments)

with dynamic iterable:
with Pool(4) as p:
pool_returns = p.imap(fcn, arguments)
(or imap_unordered)

for multiple arguments, starmap must be used

58
Q

add a command line argument

A

parser = argparse.ArgumentParser()

parser.add_argument(“-n3”, “–int_number3”, type=int, required=True, help=”required int”)

59
Q

add a command line argument which accepts mutiple inputs

A

parser.add_argument(“–numbers”, nargs=3, type=int)
parser.add_argument(“–items”, nargs=”+”)
parser.add_argument(“–items”, nargs=”*”)

60
Q

access command line arguments

A

args = parser.parse_args()

my_filename = args.filename

61
Q

fall back to the default implementation of “==” if the if-statement returns False

A

def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
return NotImplemented

62
Q

override output of the line “p1”

A

__repr__(self)

63
Q

override output of the line “print(p1)”

A

__str__(self)

64
Q

override indexing

A

__getitem__(self, key)

65
Q

override “+”

A

__add__(self, other)

66
Q

get the type of an object

A

type(dog1).__name__

67
Q

check if a variable is either an integer of a floating point number

A

isinstance(num, (int, float))

68
Q

syntax of a static method

A

@classmethod
def some_class_method(cls):
print(f”this is a class method: {cls}”)

69
Q

read file content

A

with open(“my_module.py”, “r”) as f:
print(f.read())

with open(“my_module.py”) as f:
for line in f:
print(line, end=””)

with open(“my_module.py”) as f:
while chars := f.read(10):
print(“Chunk:”)
print(chars)

70
Q

write file content

A

with open(“some_file.txt”, “w”) as f:
f.write(“This overwrites an existing file\nor creates a new one with this text!\n”)

with open(“some_file.txt”, “a”) as f:
f.write(“And here this line is appended.\n”)

with open(“some_file.txt”, “a”) as f:
print(“And another line via print()!”, file=f)

71
Q

get current working directory

A

os.getcwd()

72
Q

create a directory

A

os.makedirs(“new_directory”, exist_ok=True)

73
Q

rename files or directories

A

os.rename(“new_directory”, “my_new_new_directory”)

74
Q

remove a directory

A

os.removedirs(“my_new_new_directory”)

75
Q

remove a file

A

os.remove(“some_file.txt”)

76
Q

list all contents of a directory

A

os.listdir()

77
Q

os.path methods

A

path = os.path.join(“some”, “directory”, “filename.py”)

head, tail = os.path.split(path)

os.path.dirname(path)

os.path.basename(path)

root, ext = os.path.splitext(path) - extensions of a file

os.path.exists(path)

78
Q

check if a path is a file

A

os.path.isfile(path))

79
Q

check if a path is a directory

A

os.path.isdir(“.”) - “.” refers to the current working directory

80
Q

os.path methods

A

path = os.path.join(“some”, “directory”, “filename.py”)

head, tail = os.path.split(path)

os.path.dirname(path)

os.path.basename(path)

root, ext = os.path.splitext(path) - extensions of a file

os.path.exists(path)

os.path.abspath(path)

81
Q

list of all files and subdirectories in the current working directory

A

glob.glob(“*”)

82
Q

search the current working directory for python files

A

glob.glob(“*.py”)

83
Q

search for files and folders recursively

A

glob.glob(“**”, recursive=True)

84
Q

search in a directory and all subdirectories for python files

A

glob.glob(os.path.join(“some_folder”, “**”, “*.py”), recursive=True)

85
Q

pickle

A

import dill as pickle

always use with(“path”, “mode”) as f

pickle.dump(my_objects, f)
data = pickle.load(f)

86
Q

import modules

A

import sys

import sys as system

from os import path

import os, sys

from os import path, makedirs

from my_module import add as my_add

87
Q

create a list

A

empty_list = []

empty_list = list()

a_list = [1, 2.3456, 3, “abc”]

88
Q

navigating through nested lists

A

nested_list_element = nested_list[2][3][0]

89
Q

check if an element is contained in a list

A

“abc” in a_list

90
Q

sort lists

A

numeric_list.sort() - in-place

sorted_list = sorted(numeric_list) - numeric_list is not changed

91
Q

create a tuple

A

empty_tuple = ()

empty_tuple = tuple()

single_element_tuple = (1,)

a_tuple = 1, “2”, 3

a_tuple = (1, “2”, 3)

92
Q

create a set

A

empty_set = set()

my_set = {1, 2, 3, 3}

93
Q

add/remove elements to a set

A

my_set.add(4)

my_set.remove(2)

94
Q

common operations on sets

A

Union
new_set = my_set | {1, 4, 7}
new_set = my_set.union({1, 4, 7})

Intersection
new_set = my_set & {1, 4, 7}
new_set = my_set.intersection({1, 4, 7})

Difference
new_set = my_set - {1, 4, 7}
new_set = my_set.difference({1, 4, 7})

95
Q

create a dictionary

A

empty_dict = {}

empty_dict = dict()

some_key = “abc”
dictionary = dict(some_key=3.24, other_key=”twh”)

dictionary2 = {“stringkey”: 55, some_key: “someitem”, 23: 4}

96
Q

get all keys or values of a dictionary

A

dictionary.keys()

dictionary.values()

dictionary.items() - tuples

97
Q

additional dictionary stuff

A

Remove key and return its associated value
removed = dictionary2.pop(“stringkey”)

Get a value and use a default value if key does not exist
value = dictionary.get(“nonexistingkey”, “defaultvalue”)

98
Q

dictionary iteration

A

for key in dictionary: (Equal to: dictionary.keys())
print(key)

for value in dictionary.values():
print(value)

for key_value in dictionary.items():
print(key_value)

for key, value in dictionary.items():
print(key, value)

99
Q

list comprehensions

A

old_list = [1, 2, 3, 4, 5]
new_list = [str(i) for i in old_list]

new_list = [str(i) for i in old_list if i < 3]

new_list = [str(i) if i < 5 else “end” for i in old_list]

100
Q

reverse a list

A

reversed_list = some_list[::-1]

101
Q

unpacking

A

a, b, c, d = [1, 2, 3, 4]

a, b, *rest = [1, 2, 3, 4]

a, *rest, d = [1, 2, 3, 4]

102
Q

for loop with index

A

for i, elem in enumerate(a_tuple):
print(i, elem)

103
Q

iterate through a string with index

A

for i, char in enumerate(“hello”):
print(f”loop iteration: {i}, element: ‘{char}’”)

104
Q

integer division

A

//

floor value of a division

105
Q

string functions

A

uppercase_string = conc_strings.upper()
lowercase_string = “SILENCE!”.lower()

number_of_bla = repeated_string.count(“bla”)

separated_elements = “my-string-elements”.split(“-“)
joined_elements = “;”.join(separated_elements)

replacement = “This is a placeholder”.replace(“placeholder”, “string”)

check_for_substring = “string” in conc_strings
locate_substring = replacement.find(“is a”)

106
Q

formatted strings

A

formatted_string = “You can format floating point values as :width.precision “ \
f”{long_number:10.5f}”
another_formatted_string = f”{long_number:.{n_decimals}f}”

107
Q

console

A

print(“Hello, world!”)

my_input = input(“Please enter something: “)