Skip to content

Commit cc94bee

Browse files
committed
course 2: formating of solution 31
1 parent 0fa1499 commit cc94bee

File tree

1 file changed

+16
-17
lines changed

1 file changed

+16
-17
lines changed

course2/solutions/solution_31_multiprocessing.py

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,16 @@
44

55
import multiprocessing as mp
66

7-
def get_data_parts(N,nb_processes):
7+
def get_data_parts(N, nb_processes):
88
# Data is composed of as many sub-lists as there are processes.
99
data = [ [] for i in range(nb_processes)]
1010

1111
for i in range(N):
12-
data[ i%(nb_processes) ].append( i )
13-
14-
## Here, the trick is that we use the % operator.
15-
## For instance for 2 processes:
16-
## * If i is 3, then i%2 == 1 -> goes to sublist 1.
17-
## * If i is 4, then i%2 == 0 -> goes to sublist 0.
12+
# Here, the trick is that we use the % operator.
13+
# For instance for 2 processes:
14+
# * If i is 3, then i % 2 == 1 -> goes to sublist 1.
15+
# * If i is 4, then i % 2 == 0 -> goes to sublist 0.
16+
data[i % nb_processes].append(i)
1817
return data
1918

2019
# Let's test it out: say we have 10 points, and 2 processes.
@@ -24,29 +23,29 @@ def get_data_parts(N,nb_processes):
2423
print(data_parts)
2524

2625
# Then the task is to apply `f2` to a set of points:
27-
def f2(i , a, dx):
26+
def f2(i, a, dx):
2827
x = a + i * dx
2928
return x ** 2 - x
3029

31-
def task(data , a , dx):
30+
def task(data, a, dx):
3231
s = 0
3332
for d in data:
34-
s += f2(d , a , dx )
35-
return s*dx
33+
s += f2(d, a, dx)
34+
return s * dx
3635

37-
#let's work outside the function and focus on the main loop:
36+
# Let's work outside the function and focus on the main loop:
3837
a = 0
3938
b = 2
40-
N = 100#2 * 10**7
39+
N = 100 #2 * 10**7
4140
dx = (b - a) / N
4241

4342
data_parts = get_data_parts(N, 2)
4443

4544
# Test it on our test data.
46-
S1 , S2 = task(data_parts[0],a,dx), task(data_parts[1],a,dx)
47-
print("data parts results:",S1 , S2)
48-
# of course at the end you want to sum
49-
print("final result:", S1+S2)
45+
S1, S2 = task(data_parts[0], a, dx), task(data_parts[1], a, dx)
46+
print("data parts results:", S1, S2)
47+
# of course at the end you want to sum:
48+
print("final result:", S1 + S2)
5049

5150
# Now, to be applied with map, we will make a specific version of the task
5251
# with a and dx fixed

0 commit comments

Comments
 (0)