Data Visualization: Nice tick values

Implement the classic algorithm that charting libraries use to choose axis labels.

What to build

A program that computes nice tick values for a data interval.

Requirements

  • nice(x, round): exp = floor(log10 x), f = x / 10^exp; when rounding, n is 1 if f < 1.5, 2 if f < 3, 5 if f < 7, else 10; otherwise n is 1 if f ≤ 1, 2 if f ≤ 2, 5 if f ≤ 5, else 10. The result is n × 10^exp.
  • step = nice(nice(hi − lo, not rounding) / (count − 1), rounding); the ticks run from floor(lo / step) × step to ceil(hi / step) × step in steps of step.
  • Print the ticks on one line separated by spaces, each rounded to 10 decimals and written with Python's :g format.

Input

One line: lo hi count.

Output

One line.

Constraints

lo < hi; 2 ≤ count ≤ 20.

Example

Input:

3 97 5

Output:

0 20 40 60 80 100

Why it works

Rounding the span and then the step to 1, 2 or 5 times a power of ten gives round labels close to the requested count, and extending to whole steps makes sure every value fits on the axis.

Examples

Example 1 · Input
3 97 5
Expected output
0 20 40 60 80 100
Example 2 · Input
0.13 0.87 5
Expected output
0 0.2 0.4 0.6 0.8 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

nice(x, round) takes exp = floor(log10(x)) and f = x / 10**exp, then picks 1, 2, 5 or 10.

Hint 2

Round each tick with round(t, 10) before printing, to remove floating-point dust.

Solution

Show one correct solution (try it yourself first)
import math


def nice(x, round_it):
    exp = math.floor(math.log10(x))
    f = x / 10**exp
    if round_it:
        n = 1 if f < 1.5 else 2 if f < 3 else 5 if f < 7 else 10
    else:
        n = 1 if f <= 1 else 2 if f <= 2 else 5 if f <= 5 else 10
    return n * 10**exp


lo, hi, count = input().split()
lo, hi, count = float(lo), float(hi), int(count)
step = nice(nice(hi - lo, False) / (count - 1), True)
start = math.floor(lo / step) * step
end = math.ceil(hi / step) * step
n = round((end - start) / step)
print(" ".join(f"{round(start + i * step, 10):g}" for i in range(n + 1)))

Lesson: Scales, axes and nice ticks →