NumPy: Model np.linspace

np.linspace makes a set number of evenly spaced points. Model it, with and without the stop.

What to build

A program that prints the values and the step of np.linspace.

Requirements

  • Input: start, stop, num and True or False for endpoint. Print the values on one line, each with 4 decimal places, separated by spaces, then step: S with 4 decimal places.
  • With endpoint True the step is (stop - start) / (num - 1); with False it is (stop - start) / num. With num = 1 the only value is start and the step is nan.

Input

One line: start stop num endpoint.

Output

Two lines.

Constraints

|start|, |stop| ≤ 1000; 1 ≤ num ≤ 50.

Example

Input:

0 1 5 True

Output:

0.0000 0.2500 0.5000 0.7500 1.0000
step: 0.2500

Why it works

linspace fixes the number of points and works out the spacing from it, so the end points are exact, which a floating-point step in arange cannot promise.

Examples

Example 1 · Input
0 1 5 True
Expected output
0.0000 0.2500 0.5000 0.7500 1.0000
step: 0.2500
Example 2 · Input
0 1 5 False
Expected output
0.0000 0.2000 0.4000 0.6000 0.8000
step: 0.2000

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

Hints

Hint 1

The step is (stop - start) / (num - 1) when the stop is included, and (stop - start) / num when it is not.

Hint 2

With num = 1, the only value is the start.

Solution

Show one correct solution (try it yourself first)
parts = input().split()
start, stop, num, endpoint = float(parts[0]), float(parts[1]), int(parts[2]), parts[3] == "True"
if num == 1:
    values = [start]
    step_text = "nan"
else:
    step = (stop - start) / ((num - 1) if endpoint else num)
    values = [start + i * step for i in range(num)]
    step_text = f"{step:.4f}"
print(" ".join(f"{v:.4f}" for v in values))
print("step: " + step_text)

Lesson: Creating arrays →