Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Index into an Infinite String in Python
Sometimes we need to extract a substring from an infinite repetition of a given string. Python's modulo operator makes this straightforward by cycling through the original string's indices.
Given a string s and two integers i and j where i < j, we need to find the substring from an infinite string formed by repeating s forever, using indices [i, j).
Example Problem
If s = "programmer", i = 4, and j = 8, the infinite string looks like:
"programmerprogrammerprogrammer..." 0123456789012345678901234567890...
We need the substring from index 4 to 7 (excluding 8), which gives us "ramm".
Solution Approach
The key insight is using the modulo operator to map any index back to the corresponding position in the original string:
- Initialize an empty result string
- For each index from
itoj-1, find the corresponding character usings[index % len(s)] - Concatenate each character to build the result
Implementation
class Solution:
def solve(self, s, i, j):
p = ""
for t in range(i, j):
p += s[t % len(s)]
return p
# Test the solution
ob = Solution()
s = "programmer"
i = 4
j = 8
print(ob.solve(s, i, j))
ramm
How It Works
Let's trace through the example step by step:
s = "programmer" # length = 10
i = 4
j = 8
# For each index from 4 to 7:
# t=4: s[4 % 10] = s[4] = 'r'
# t=5: s[5 % 10] = s[5] = 'a'
# t=6: s[6 % 10] = s[6] = 'm'
# t=7: s[7 % 10] = s[7] = 'm'
# Result: "ramm"
for t in range(4, 8):
char = s[t % len(s)]
print(f"Index {t}: s[{t % len(s)}] = '{char}'")
Index 4: s[4] = 'r' Index 5: s[5] = 'a' Index 6: s[6] = 'm' Index 7: s[7] = 'm'
Alternative Implementation
For better performance with large ranges, we can use list comprehension and join:
def get_infinite_substring(s, i, j):
return ''.join(s[t % len(s)] for t in range(i, j))
# Test with the same example
s = "programmer"
result = get_infinite_substring(s, 4, 8)
print(result)
# Test with a larger range
result2 = get_infinite_substring("abc", 0, 10)
print(result2)
ramm abcabcabca
Conclusion
Use the modulo operator to map infinite string indices back to the original string positions. This approach efficiently handles any range without creating the actual infinite string in memory.
