Python hacks Flashcards

(11 cards)

1
Q

Simple tying example for addition function

A
def add(a: int, b: int) -> int:
return a+b
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Iterate through list with indices

A
for i, x in enumerate(list_ab):
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Iterate through multiple iterables in parallel

A
a = [1, 2, 3]
b = [10, 20, 30]
for x, y in zip(a, b):
    print(x + y)   
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Dictionary that adds keys if they are not included

A

```
from collections import defaultdict
counts = defaultdict(int)
for ch in “banana”:
counts[ch] += 1
~~~

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

What should you be careful about when iterating over a list?

A

Changing the list while iterating it will also change the iteration, instead iterate over a copy

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

Create a defaultdict with values

A
from collections import defaultdict
d = {"a": [1, 2], "b": [9]}
groups = defaultdict(list, d)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to get more info on a function?

A
help(torch.where) #python
torch.where? #Jupyter
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to give a selection of arguments?

A

``` from typing import Literal

Reduction = Literal[“none”, “mean”, “sum”]

def my_loss(x, reduction: Reduction = “mean”):

~~~

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

How to type optional arguments?

A

```
Optional[torch.Tensor]
x: torch.Tensor | None = None
~~~

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

What are common types in PyTorch?

A
def forward_pass(model: nn.Module, x: torch.Tensor) -> torch.Tensor:
    return model(x)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to get infinity and -infinity?

A
neg_inf = float("-inf")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly