Skip to content

Commit c5f923d

Browse files
Update Prefix_Sums.mdx
1 parent 73d622b commit c5f923d

File tree

1 file changed

+28
-10
lines changed

1 file changed

+28
-10
lines changed

content/3_Silver/Prefix_Sums.mdx

+28-10
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,6 @@ These are also known as
185185
## Solution - Static Range Sum
186186

187187
<LanguageSection>
188-
189188
<CPPSection>
190189

191190
In C++ we can use
@@ -223,7 +222,6 @@ int main() {
223222
```
224223
225224
</CPPSection>
226-
227225
<JavaSection>
228226
229227
```java
@@ -269,20 +267,17 @@ public class Main {
269267
```
270268
271269
</JavaSection>
272-
273270
<PySection>
274271
275-
In Python you can use [itertools.accumulate](https://docs.python.org/3.6/library/itertools.html#itertools.accumulate). Note that you have to call list() since accumulate returns a [generator](https://wiki.python.org/moin/Generators). The first value returned is that of the iterable passed, so we add a zero in the front (in newer versions you can give the optional parameter of initial=0).
276-
277272
```py
278273
# import itertools
279274

280275

281276
def psum(a):
282277
psum = [0]
283278
for i in a:
284-
psum.append(psum[-1] + i) # psum[-1] is the last element in the list
285-
return psum # Or with itertools.accumulate: [0] + list(itertools.accumulate(a))
279+
psum.append(psum[-1] + i)
280+
return psum
286281

287282

288283
N, Q = map(int, input().split())
@@ -294,8 +289,31 @@ for i in range(Q):
294289
print(p[r] - p[l])
295290
```
296291
297-
</PySection>
292+
An alternative approach is to use [`itertools.accumulate`](https://docs.python.org/3/library/itertools.html#itertools.accumulate).
293+
294+
The first value returned is that of the iterable passed, so we add a zero in the front.
295+
Note that in newer versions you can give the optional parameter `initial=0`.
296+
297+
```py
298+
import itertools
299+
300+
301+
def psum(a):
302+
return [0] + list(itertools.accumulate(a))
298303

304+
305+
# BeginCodeSnip{Same code as above}
306+
N, Q = map(int, input().split())
307+
a = list(map(int, input().split()))
308+
p = psum(a)
309+
310+
for i in range(Q):
311+
l, r = map(int, input().split())
312+
print(p[r] - p[l])
313+
# EndCodeSnip
314+
```
315+
316+
</PySection>
299317
</LanguageSection>
300318
301319
## Problems
@@ -304,8 +322,8 @@ for i in range(Q):
304322
305323
<Warning>
306324
307-
"Haybale Stacking" isn't submittable on the USACO website. Use
308-
[this link](https://www.spoj.com/problems/HAYBALE/) to submit.
325+
"Haybale Stacking" isn't submittable on the USACO website;
326+
Use [this link](https://www.spoj.com/problems/HAYBALE/) to submit instead.
309327
310328
</Warning>
311329

0 commit comments

Comments
 (0)