Skip to content

Commit 1828518

Browse files
Merge pull request #4554 from Pramad712/patch-10
Add built-in approach for Prefix sums
2 parents ef2ac82 + 7ec1fac commit 1828518

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

content/3_Silver/Prefix_Sums.mdx

+26-7
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,14 +267,13 @@ public class Main {
269267
```
270268
271269
</JavaSection>
272-
273270
<PySection>
274271
275272
```py
276273
def psum(a):
277274
psum = [0]
278275
for i in a:
279-
psum.append(psum[-1] + i) # psum[-1] is the last element in the list
276+
psum.append(psum[-1] + i)
280277
return psum
281278

282279

@@ -289,8 +286,30 @@ for i in range(Q):
289286
print(p[r] - p[l])
290287
```
291288
292-
</PySection>
289+
An alternative approach is to use [`itertools.accumulate`](https://docs.python.org/3/library/itertools.html#itertools.accumulate).
290+
Notice that we need to add a $0$ to the front of the array.
291+
If using a newer version, you can use the optional parameter `initial=0` as well.
292+
293+
```py
294+
import itertools
295+
296+
297+
def psum(a):
298+
return [0] + list(itertools.accumulate(a))
299+
293300

301+
# BeginCodeSnip{Same code as above}
302+
N, Q = map(int, input().split())
303+
a = list(map(int, input().split()))
304+
p = psum(a)
305+
306+
for i in range(Q):
307+
l, r = map(int, input().split())
308+
print(p[r] - p[l])
309+
# EndCodeSnip
310+
```
311+
312+
</PySection>
294313
</LanguageSection>
295314
296315
## Problems
@@ -299,8 +318,8 @@ for i in range(Q):
299318
300319
<Warning>
301320
302-
"Haybale Stacking" isn't submittable on the USACO website. Use
303-
[this link](https://www.spoj.com/problems/HAYBALE/) to submit.
321+
"Haybale Stacking" isn't submittable on the USACO website;
322+
Use [this link](https://www.spoj.com/problems/HAYBALE/) to submit instead.
304323
305324
</Warning>
306325

0 commit comments

Comments
 (0)