np.arange is range for arrays. Model it, including counting down and empty results.
What to build
A program that prints what np.arange(start, stop, step) returns.
Requirements
- Print the values from start, in steps of step, stopping before stop, in NumPy's 1-D print format: square brackets, numbers right-aligned to the widest one, separated by single spaces; an empty result prints
[]. - If the step is 0, print
ZeroDivisionError: step cannot be zero.
Input
One line: start, stop and step, whole numbers.
Output
One line.
Constraints
|start|, |stop| ≤ 1000; the result has at most 200 values.
Example
Input:
0 10 3
Output:
[0 3 6 9]
Why it works
arange keeps going only while the next value has not reached the stop in the step's direction, so a step pointing away from the stop gives an empty array.
Examples
Example 1 · Input
0 10 3
Expected output
[0 3 6 9]
Example 2 · Input
5 -6 -5
Expected output
[ 5 0 -5]
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep adding the step while the value is still before the stop, in the direction of the step.
Hint 2
A step of 0 is an error, as in NumPy.
Solution
Show one correct solution (try it yourself first)
start, stop, step = map(int, input().split())
if step == 0:
print("ZeroDivisionError: step cannot be zero")
else:
values = []
x = start
while (step > 0 and x < stop) or (step < 0 and x > stop):
values.append(x)
x += step
if not values:
print("[]")
else:
width = max(len(str(v)) for v in values)
print("[" + " ".join(str(v).rjust(width) for v in values) + "]")