Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
Kernel: Python 3

Rolling operators

Code examples from Think Complexity, 2nd edition.

Copyright 2019 Allen Downey, MIT License

%matplotlib inline import numpy as np import pandas as pd

Exercise: Write a Python function that takes a sequence and an integer k and computes the "rolling sum", which is sum of each subset of k consecutive elements. For example:

>>> t = [1, 2, 3, 4, 5] >>> rolling_sum(t, 3) [6, 9, 12]

You can use any language features you want: pure Python, NumPy, Pandas, or SciPy.

# Solution goes here
t = [1, 2, 3, 4, 5] rolling_sum(t, 3)

Exercise: Rewrite the previous example using a list comprehension.

# Solution goes here
t = [1, 2, 3, 4, 5] rolling_sum(t, 3)

Exercise: Write a version using np.correlate.

# Solution goes here
rolling_sum(t, 3)

Exercise: Write a version using scipy.signal.correlate.

from scipy.signal import correlate
# Solution goes here
rolling_sum(t, 3)

Exercise: Write a version using pd.Series.rolling().

s = pd.Series(t)
r = s.rolling(3) r
r.sum().dropna()
r.sum().dropna().values
# Solution goes here
rolling_sum(t, 3)