Index into an Infinite String in Python


Suppose we have a string s and two integers i and j (i < j). Now suppose p is an infinite string of s repeating forever. We have to find the substring of p from indexes [i, j).

So, if the input is like s = "programmer", i = 4, j = 8, then the output will be "ramm".

To solve this, we will follow these steps −

  • p:= blank string
  • for t in range i to j, do
    • p := p concatenate a character from s at index (t mod size of s)
  • return p

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, i, j):
      p=""
      for t in range(i,j):
         p+=s[t%len(s)]
      return p
ob = Solution()
s = "programmer"
i = 4
j = 8
print(ob.solve(s, i, j))

Input

"programmer", 4, 8

Output

ramm

Updated on: 23-Sep-2020

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements