One a Day One Liners with Python — Week 8

Computing Sequences & Series

Jeremy Brown
2 min readFeb 20, 2023
Photo by Tom Wilson on Unsplash

Now would be a good time to cue up some Math Rock because this week we’re going to see just how much numerical havoc we can wreak with One Liner computations.

All of the code for this series can be found here.

Update: After 52 days of One Liners, I hit a bit of writer’s block or something. I’m gonna take a short hiatus for the next week and let the One a Day One Liner batteries recharge.

Feb 21, 2023

Compute a range of digits from the Fibonacci Sequence 2️⃣ 3️⃣ 5️⃣

from math import sqrt

n1 = 1
n2 = 20
sq5 = sqrt(5)
phi = (1 + sq5) / 2
fib = [int(round(pow(phi, i) / sq5)) for i in range(n1, n2)]

Feb 20, 2023

Find the partial sum of an exponential sequence 🤯

cubed = [i**3 for i in range(10)]
partial = [sum(cubed[:i+1]) for i in range(len(cubed))]

Feb 19, 2023

Compute an arithmetic series 🧮

start, end, diff = 5, 100, 5

# A viable, yet naive approach
series = sum([i for i in range(start, end+1, diff)])

# Purely analytical solution
series = ((((end-start)/diff)+1) * (start+end)) * 0.5

We’ll start the week off lightly. An arithmetic series is simply the sum of a sequence of evenly distributed numbers. For example:

1 + 3 + 5 + 7 = 16

The two solutions above yield the same results. The second one is probably preferable as it doesn’t require a loop. The first half derives the number of terms in the sequence and the second half calculates the average between the start and end. Multiply those two values together and you get the sum of the sequence (i.e. the arithmetic series).

--

--

Jeremy Brown

Software Engineer, originally from the U.S. and now living and working in Vienna, Austria. I write about Programming, Music, Machine Learning & NLP