Skip to content

Instantly share code, notes, and snippets.

@katrielalex
Created February 6, 2018 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katrielalex/3f65dd050c407ab53300a33ad4490f8f to your computer and use it in GitHub Desktop.
Save katrielalex/3f65dd050c407ab53300a33ad4490f8f to your computer and use it in GitHub Desktop.
Print strings colored by character frequency
#!/usr/bin/env python3
from itertools import accumulate, chain, repeat, tee
import click
import collections
import crayons
import split
COLORS = "red yellow blue white".split()
# http://wordaligned.org/articles/slicing-a-list-evenly-with-python
def chunk(xs, n):
assert n > 0
L = len(xs)
s, r = divmod(L, n)
widths = chain(repeat(s+1, r), repeat(s, n-r))
offsets = accumulate(chain((0,), widths))
b, e = tee(offsets)
next(e)
return [xs[s] for s in map(slice, b, e)]
@click.command()
@click.argument('s')
def main(s):
n = len(COLORS)
freqs = collections.Counter(s)
chunks = chunk(list(freqs), n)
assert n == len(chunks) # sanity check
# index of the frequency bucket containing a character
freq_bucket = lambda c: min(i for i, chunk in enumerate(chunks) if c in chunk)
colored = lambda c: getattr(crayons, COLORS[freq_bucket(c)])(c)
for c in s:
print(colored(c), end='')
print()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment