@@ -185,7 +185,6 @@ These are also known as
185
185
## Solution - Static Range Sum
186
186
187
187
<LanguageSection>
188
-
189
188
<CPPSection>
190
189
191
190
In C++ we can use
@@ -223,7 +222,6 @@ int main() {
223
222
` ` `
224
223
225
224
</CPPSection>
226
-
227
225
<JavaSection>
228
226
229
227
` ` ` java
@@ -269,14 +267,13 @@ public class Main {
269
267
` ` `
270
268
271
269
</JavaSection>
272
-
273
270
<PySection>
274
271
275
272
` ` ` py
276
273
def psum (a ):
277
274
psum = [0 ]
278
275
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 )
280
277
return psum
281
278
282
279
@@ -289,8 +286,30 @@ for i in range(Q):
289
286
print (p [r ] - p [l ])
290
287
` ` `
291
288
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
+
293
300
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>
294
313
</LanguageSection>
295
314
296
315
## Problems
@@ -299,8 +318,8 @@ for i in range(Q):
299
318
300
319
<Warning>
301
320
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 .
304
323
305
324
</Warning>
306
325
0 commit comments