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?
start = 8 stop = 0 step = -2 for index in range(start, stop, step): print(index) # prints 8, 6, 4 and 2 converted_start = ... # convert `start` converted_start = ... # convert `stop` converted_step = -step # convert `step` for index in range(converted_start, converted_stop, converted_step): print(index) # prints 2, 4, 6 and 8
Advertisement
Answer
Here come the formula:
def reverse_range(start, stop, step): new_start_offset = (stop - start) % step if new_start_offset == 0: new_start_offset = step new_start = stop - new_start_offset new_stop = start - step new_step = -step return new_start, new_stop, new_step
Here come the tests:
def print_range(start, stop, step): for i in range(start, stop, step): print(i, end=',') print() print_range(0, 8, 2) 0,2,4,6, print_range(*reverse_range(0,8,2)) 6,4,2,0, print_range(0, 9, 2) 0,2,4,6,8, print_range(*reverse_range(0,9,2)) 8,6,4,2,0, print_range(8, 0, -2) 8,6,4,2, print_range(*reverse_range(8, 0, -2)) 2,4,6,8, print_range(9, 0, -2) 9,7,5,3,1, print_range(*reverse_range(9, 0, -2)) 1,3,5,7,9,