Python – Incremental Size Chunks from Strings
Last Updated :
15 May, 2023
Given a String, split it into incremental sizes consecutive list.
Input : test_str = ‘geekforgeeks is best’
Output : [‘g’, ‘ee’, ‘kfo’, ‘rgee’, ‘ks is’, ‘ best’]
Explanation : Characters size increasing in list.
Input : test_str = ‘geekforgeeks’
Output : [‘g’, ‘ee’, ‘kfo’, ‘rgee’, ‘ks’]
Explanation : Characters size increasing in list.
Method #1 : Using loop + slicing
In this, we perform task of getting chunks using string slicing and keep on increasing chunk size during iteration.
Python3
test_str = 'geekforgeeks is best for geeks'
print ( "The original string is : " + str (test_str))
res = []
idx = 1
while True :
if len (test_str) > idx:
res.append(test_str[ 0 : idx])
test_str = test_str[idx:]
idx + = 1
else :
res.append(test_str)
break
print ( "The Incremental sized Chunks : " + str (res))
|
Output
The original string is : geekforgeeks is best for geeks
The Incremental sized Chunks : ['g', 'ee', 'kfo', 'rgee', 'ks is', ' best ', 'for gee', 'ks']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using generator + slicing
In this, we perform slicing as in above method, difference is that chunks are rendered using generator expression, each chunk yields at runtime in loop.
Python3
def gen_fnc(test_str):
strt = 0
stp = 1
while test_str[strt : strt + stp]:
yield test_str[strt : strt + stp]
strt + = stp
stp + = 1
test_str = 'geekforgeeks is best for geeks'
print ( "The original string is : " + str (test_str))
res = list (gen_fnc(test_str))
print ( "The Incremental sized Chunks : " + str (res))
|
Output
The original string is : geekforgeeks is best for geeks
The Incremental sized Chunks : ['g', 'ee', 'kfo', 'rgee', 'ks is', ' best ', 'for gee', 'ks']
Time Complexity: O(n)
Space Complexity: O(n)
Method 3: Using recursion.
Python3
def recursive_fnc(test_str, res, strt = 0 , stp = 1 ):
if not test_str[strt:strt + stp]:
return res
else :
res.append(test_str[strt:strt + stp])
return recursive_fnc(test_str, res, strt + stp, stp + 1 )
test_str = 'geekforgeeks is best for geeks'
print ( "The original string is : " + str (test_str))
res = recursive_fnc(test_str, [])
print ( "The Incremental sized Chunks : " + str (res))
|
Output
The original string is : geekforgeeks is best for geeks
The Incremental sized Chunks : ['g', 'ee', 'kfo', 'rgee', 'ks is', ' best ', 'for gee', 'ks']
The time complexity of this approach is also O(n^2), where n is the length of the input string.
The space complexity is O(n), as the function generates chunks one at a time and stores them in a list.
Share your thoughts in the comments
Please Login to comment...