Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#%% example -- can't change iterator during for loop, formatting display
for i in range(10):
print(f'i is {i}, trying to change it to {3*i}')
i = 3*i # don't do this (trying to change an iterator in a for loop)
#%% example -- find largest number divisible with 7 and smaller than 100
i = 1
while i*7<100:
i = i+1
print(7*i) # this will be larger than 100 -- so condition from while does not hold
#%% example -- vectorization
import numpy as np
test = np.array([3, 4, 8, 6, 5, 8, 3, 4, 7, 8, 8, 9, 4, 1, 3, 4, 6, 7, 9, 5, 3, 5, 7, 2, 5, 3])
## I want to count how many times does 8 appear in test
# One way of achieving this
count = 0
for t in test:
if t==8:
count += 1
# A better way of achieving this
count = (test==8).sum()
#%% I want to count how many times does each digit appear in test
# One way of achieving this
hist = np.zeros(10, dtype='int')
for i in range(len(hist)):
hist[i] = (test==i).sum()
# Another way of achieving this
hist = np.zeros(10, dtype='int')
for t in test:
hist[t] += hist[t]
#%% Avoid using break for better readability, if possible
# Without break: readable code, easly to see when while loop stops
i = 0
while i<101:
i = i+1
print(i, end= ' ')
# With break: may be difficult to see when loop stops (especially in loops spanning many lines)
i = 0
while True:
i = i+1
print(i, end= ' ')
if i>100:
break