Program to implement run length string decoding iterator class in Python

PythonServer Side ProgrammingProgramming

Suppose we want to define an iterator class that constructs with a run-length encoded lowercase string say s, there are two functions for this iterator they are −

  • next() this finds the next element in the iterator
  • hasnext() this checks whether the next element is present or not

So, if the input is like s = "2b1a", then construct an object with s, then call next(), hasnext(), next(), next(), hasnext(), then the output will be "b", True, "b", "a", False.

To solve this, we will follow these steps −

  • Define a constructor. This will take s
  • output := a new list
  • num := blank string
  • for each i in s, do
    • if i is alphabetic, then
      • insert num at the end of output
      • insert i at the end of output
      • num := blank string
    • otherwise,
      • num := num + i
  • Define a function next().
  • if hasnext() is true, then
    • count := output[0]
    • letter := output[1]
    • count := count - 1
    • if count > 0, then
      • output[0] := output[0] - 1
    • otherwise,
      • output := output[from index 2 to end]
    • return letter
  • Define a function hasnext().
  • if size of output is not 0, then
    • return True
  • return False

Example

Let us see the following implementation to get better understanding −

class RunLengthIterator:
   def __init__(self, s):
     self.output = []
     num = ""
     for i in s:
         if i.isalpha():
            self.output.append(int(num))
            self.output.append(i)
            num = ""
         else:
            num += i

   def next(self):
      if self.hasnext():
         count = self.output[0]
         letter = self.output[1]
         count -= 1
         if count > 0:
            self.output[0] -= 1
         else:
            self.output = self.output[2:]
         return letter

   def hasnext(self):
      if len(self.output) != 0:
         return True
      return False

s = "2b1a"
obj = RunLengthIterator(s)
print(obj.next())
print(obj.hasnext())
print(obj.next())
print(obj.next())
print(obj.hasnext())

Input

"2b1a"
obj = RunLengthIterator(s)
obj.next()
obj.hasnext()
obj.next()
obj.next()
obj.hasnext()

Output

b
True
b
a
False
raja
Updated on 14-Oct-2021 09:44:59

Advertisements