Given the start
, stop
and step
values, where start
> stop
and step
< 0
, how can I convert the values so that start
< stop
and step
> 0
and use these values in a for loop that can yield the same index but in a reverse way. In other words, what should be the mathematical formula to use to set variables converted_start
and converted_stop
below?
JavaScript
x
15
15
1
start = 8
2
stop = 0
3
step = -2
4
5
for index in range(start, stop, step):
6
print(index) # prints 8, 6, 4 and 2
7
8
9
converted_start = # convert `start`
10
converted_start = # convert `stop`
11
converted_step = -step # convert `step`
12
13
for index in range(converted_start, converted_stop, converted_step):
14
print(index) # prints 2, 4, 6 and 8
15
Advertisement
Answer
Here come the formula:
JavaScript
1
9
1
def reverse_range(start, stop, step):
2
new_start_offset = (stop - start) % step
3
if new_start_offset == 0:
4
new_start_offset = step
5
new_start = stop - new_start_offset
6
new_stop = start - step
7
new_step = -step
8
return new_start, new_stop, new_step
9
Here come the tests:
JavaScript
1
25
25
1
def print_range(start, stop, step):
2
for i in range(start, stop, step):
3
print(i, end=',')
4
print()
5
6
print_range(0, 8, 2)
7
0,2,4,6,
8
print_range(*reverse_range(0,8,2))
9
6,4,2,0,
10
11
print_range(0, 9, 2)
12
0,2,4,6,8,
13
print_range(*reverse_range(0,9,2))
14
8,6,4,2,0,
15
16
print_range(8, 0, -2)
17
8,6,4,2,
18
print_range(*reverse_range(8, 0, -2))
19
2,4,6,8,
20
21
print_range(9, 0, -2)
22
9,7,5,3,1,
23
print_range(*reverse_range(9, 0, -2))
24
1,3,5,7,9,
25