Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Divide String into Equal K chunks

Python – Divide String into Equal K chunks

Given a String perform division into K equal chunks.

Input : test_str = ‘Lazyroarforgeek’, K = 4 
Output : [‘gee’, ‘ksf’, ‘org’, ‘eek’] 
Explanation : 12/4 = 3, length of each string extracted. 

Input : test_str = ‘Lazyroarforgeek’, K = 1 
Output : [‘Lazyroarforgeek’] 
Explanation : 12/1 = 12, whole string is single chunk.

Method #1: Using len() + loop

In this, we first perform task of computation of length of each chunk required from K and string length, post that,  string is splitted on desired indices to extract chunks using slicing.

Python3




# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using len() + loop
 
# initializing strings
test_str = 'neveropen 1'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 5
 
# compute chunk length
chnk_len = len(test_str) // K
 
res = []
for idx in range(0, len(test_str), chnk_len):
     
    # appending sliced string
    res.append(test_str[idx : idx + chnk_len])
     
 
# printing result
print("The K chunked list : " + str(res))


Output

The original string is : neveropen 1
The K chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using list comprehension

The method similar to above, difference being that last process is encapsulated to one-liner list comprehension.

Python3




# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using list comprehension
 
# initializing strings
test_str = 'neveropen 1'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 5
 
# compute chunk length
chnk_len = len(test_str) // K
 
# one-liner to perform the task
res = [test_str[idx : idx + chnk_len] for idx in range(0, len(test_str), chnk_len)]
 
# printing result
print("The K len chunked list : " + str(res))


Output

The original string is : neveropen 1
The K len chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3: Using the string slicing technique in a loop

This solution uses a loop and string slicing to divide the string into equal chunks of length chnk_len. The for loop iterates through the string with a step size of chnk_len, and slices the string into chunks of length chnk_len. The chunks are then appended to an empty list res. Finally, the list res is printed to display the chunks.

Python3




# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using string slicing in a loop
 
# initializing strings
test_str = 'neveropen 1'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 5
 
# compute chunk length
chnk_len = len(test_str) // K
 
# initialize an empty list to store the chunks
res = []
 
# loop through the string and slice it into chunks of length chnk_len
for i in range(0, len(test_str), chnk_len):
    res.append(test_str[i:i+chnk_len])
 
# printing result
print("The K len chunked list : " + str(res))


Output

The original string is : neveropen 1
The K len chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']

Time complexity: O(n), where n is the length of the input string test_str. 
Auxiliary space: O(k), where k is the number of chunks.

Method 4: Using itertools.islice()

  1. Import the itertools module.
  2. Initialize an empty list to store the chunks.
  3. Compute the chunk length chnk_len by dividing the length of the input string by K.
  4. Use the itertools.islice() method to iterate through the input string in chunks of length chnk_len.
  5. Append each chunk to the list of chunks.
  6. If the length of the input string is not evenly divisible by K, there will be one final chunk of smaller length.
  7. Append this final chunk to the list of chunks.
  8. Return the list of chunks.

Python3




# Python3 code to demonstrate working of
# Divide String into Equal K chunks
# Using string slicing in a loop
 
# initializing strings
test_str = 'neveropen 1'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 5
 
# compute chunk length
chnk_len = len(test_str) // K
 
# initialize an empty list to store the chunks
res = []
 
# loop through the string and slice it into chunks of length chnk_len
for i in range(0, len(test_str), chnk_len):
    res.append(test_str[i:i+chnk_len])
 
# append the final chunk to the list of chunks if the length of the input string is not evenly divisible by K
if len(test_str) % K != 0:
    res.append(test_str[-(len(test_str) % chnk_len):])
 
# printing result
print("The K len chunked list : " + str(res))


Output

The original string is : neveropen 1
The K len chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(k), where k is the number of chunks.

Method #5: Using regular expression

Steps:

  1. Import the re module to use the regular expression.
  2. Initialize the string and the value of K.
  3. Compute the length of each chunk.
  4. Use re.findall() to split the string into equal chunks of length chnk_len.
  5. Print the resulting list of chunks.

Python3




import re
 
# initializing strings
test_str = 'neveropen 1'
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing K
K = 5
 
# compute chunk length
chnk_len = len(test_str) // K
 
# using regular expression to split the string into equal chunks
res = re.findall('.' * chnk_len, test_str)
 
# printing result
print("The K len chunked list : " + str(res))


Output

The original string is : neveropen 1
The K len chunked list : ['gee', 'ksf', 'org', 'eek', 's 1']

Time complexity: O(n), where n is the length of the input string.

Auxiliary space: O(n/K), where K is the number of equal chunks.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments