SoFunction
Updated on 2024-11-15

How python implements reverse iteration

This article example for you to share the python implementation of the reverse iteration of the specific code for your reference, the details are as follows

Case in point:

Implement a sequential floating point number generator, FloatRange, that produces a number of columns of floating point numbers based on a given range (start, end) and step value, e.g., FloatRange(3,4,0.2), which will produce the following sequence:

Positive: 3.0 3.2 ...... 4.0

Reverse: 4.0 3.8 ...... 3.0

How is this achieved?

Method 1: List Flip

#!/usr/bin/python3
 
l = [1, 2, 3, 4, 5, 6]
()
for i in l:
  print(i)
   
# Problems have arisen, changing the original list, not desirable

Method 2: List Slicing

#!/usr/bin/python3
 
l = [1, 2, 3, 4, 5, 6]
for i in l[::-1]:
  print(i)
   
# Got a list the size of the original list, which is somehow wasteful #

Method 3: __ reversed__ method

#!/usr/bin/python3
 
l = [1, 2, 3, 4, 5, 6]
 
for i in reversed(l):
  print(i)

How to organize logically?

The forward iteration of the for loop calls the __iter__ method and the reverse iteration calls the __reversed__ method, so you can define a class that writes these methods

#!/usr/bin/python3
 
 
class FloatRange(object):
  def __init__(self, start, end, step):
     = self.__get_dot_num(step)
    # Multiply as many decimal places as there are powers of 10, because floating point numbers are inaccurate and are converted to plastic numbers for calculation.
     = start*pow(10, )
     = end*pow(10, )
     = step*pow(10, )
     
  def __get_dot_num(self, step):
    # Calculate how many decimal places there are in STEP #
    if isinstance(step, int):
      return step
    else:
      # Calculate how many decimal places there are by round, first of its kind
      for dot in range(len(str(step))+1):
        if step == round(step, dot):
          return dot
 
  def __iter__(self):
    # Forward iteration
    while  <= :
      yield /pow(10, )
       += 
 
  def __reversed__(self):
    # Reverse iteration
    while  >= :
      yield /pow(10,)
       -= 
 
if __name__ == '__main__':
   
  float_num_1 = FloatRange(2, 5, 0.1)
  float_num_2 = FloatRange(2, 5, 0.1)
   
  # Forward iteration
  for i in float_num_1:
    print(i)
     
  print('_'*60)
   
  # Reverse iteration
  for x in reversed(float_num_2):
    print(x)

This is the whole content of this article.