![]() |
VOOZH | about |
The iteration of numbers is done by looping techniques in python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backwards in alternate way and having shorthands to do so can be quite useful. Let’s discuss certain ways in which this can be done.
Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting.
The reversed numbers are : 6 4 2 0
Time complexity: O(N)
Auxiliary space: O(1)
Method #2 : Using range(N, -1, -2) This particular task can also be performed using the conventional range function which, if provided with the third argument performs the alternate skip and second argument is used to start from backwards.
The reversed numbers are : 6 4 2 0
Time complexity: O(N/2), where N is the value of the variable N.
Auxiliary space: O(1), as we are not using any additional data structure to store the values.
Method 3: use list comprehension
The reversed numbers are: 6 4 2 0
Time complexity: O(N/2) for generating the list and O(N) for joining the elements,
Auxiliary space: O(N) for storing the list. However, it may be slightly less efficient than the other methods due to the overhead of creating and joining a list.
Method 4: Using a while loop
Step-by-step approach:
The numbers are: 6 4 2 0
Time Complexity: O(N/2), as we iterate through N/2 numbers, where N is the starting number.
Auxiliary Space: O(1), as we only use a constant amount of extra memory to store the num variable.