Skip to content

Instantly share code, notes, and snippets.

@dododas
Last active Nov 1, 2015
Embed
What would you like to do?
Python generator for the sequence 1, 2,.., 9, 10, 20,.., 90, 100, 200,..,.
#!/usr/bin/env python3
'''
A python generator for the sequence 1, 2,.., 9, 10, 20,.., 90, 100, 200,.. up to n_max
Created by: Raibatak Das
'''
from math import floor, log10
def logseq(n_max):
k = 1;
while (k <= n_max):
yield k
k += int( 10**floor(log10(k)) )
## Examples:
# Generate tick mark locations for a logarithmic axis in a plot
n_max = 500
list(logseq(n_max))
# Compute cumulative sum of the sequence
from itertools import accumulate
n_max = 10000
vals = list(logseq(n_max))
cumulsum = list(accumulate(vals))
# Plot cumulative sum
import matplotlib.pyplot as plt
plt.figure(facecolor="w")
plt.semilogy(cumulsum, "o:")
plt.xlabel("index")
plt.ylabel("cumulative sum")
plt.title("1 + 2 + ... + 9 + 10 + 20 + ... + 90 + 100 + ...")
plt.grid(True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment