Python program to get all possible slices of a string for K number of slices
Last Updated :
18 May, 2023
Given a string, the task is to write a Python program to get all possible slices for K number of slices.
Input : test_str = “Gfg4all”, K = 3
Output : [[‘G’, ‘f’, ‘g4all’], [‘G’, ‘fg’, ‘4all’], [‘G’, ‘fg4’, ‘all’], [‘G’, ‘fg4a’, ‘ll’], [‘G’, ‘fg4al’, ‘l’], [‘Gf’, ‘g’, ‘4all’], [‘Gf’, ‘g4’, ‘all’], [‘Gf’, ‘g4a’, ‘ll’], [‘Gf’, ‘g4al’, ‘l’], [‘Gfg’, ‘4’, ‘all’], [‘Gfg’, ‘4a’, ‘ll’], [‘Gfg’, ‘4al’, ‘l’], [‘Gfg4’, ‘a’, ‘ll’], [‘Gfg4’, ‘al’, ‘l’], [‘Gfg4a’, ‘l’, ‘l’]]
Explanation : All possible 3 slices for constructing string are returned.
Input : test_str = “Gfg4all”, K = 2
Output : [[‘G’, ‘fg4all’], [‘Gf’, ‘g4all’], [‘Gfg’, ‘4all’], [‘Gfg4’, ‘all’], [‘Gfg4a’, ‘ll’], [‘Gfg4al’, ‘l’]]
Explanation : All possible 2 slices for constructing string are returned.
Method #1 : Using list comprehension + slicing + loop
In this, consecutive slices are computed incrementally starting from size 1. The last element is always split into 2 in all the ways in acc. to other strings.
Python3
test_str = "Gfg4all"
print ( "The original string is : " + str (test_str))
K = 3
res = [[test_str]]
for idx in range (K - 1 ):
res = [[ * strt, end[:y], end[y:]] for * strt, end in res
for y in range ( 1 , len (end) - K + idx + 2 )]
print ( "All possible slices for K strings : " + str (res))
|
Output
The original string is : Gfg4all
All possible slices for K strings : [['G', 'f', 'g4all'], ['G', 'fg', '4all'], ['G', 'fg4', 'all'], ['G', 'fg4a', 'll'], ['G', 'fg4al', 'l'], ['Gf', 'g', '4all'], ['Gf', 'g4', 'all'], ['Gf', 'g4a', 'll'], ['Gf', 'g4al', 'l'], ['Gfg', '4', 'all'], ['Gfg', '4a', 'll'], ['Gfg', '4al', 'l'], ['Gfg4', 'a', 'll'], ['Gfg4', 'al', 'l'], ['Gfg4a', 'l', 'l']]
Method #2 : Using combinations() + zip() + list comprehension
In this, combinations is used to get all possible substrings for the ranges computed using slicing during iteration.
Python3
from itertools import combinations
test_str = "Gfg4all"
print ( "The original string is : " + str (test_str))
K = 3
res = [[test_str[idx: j] for idx, j in zip ([ None , * sub], [ * sub, None ])]
for sub in combinations( range ( 1 , len (test_str)), K - 1 )]
print ( "All possible slices for K strings : " + str (res))
|
Output
The original string is : Gfg4all
All possible slices for K strings : [['G', 'f', 'g4all'], ['G', 'fg', '4all'], ['G', 'fg4', 'all'], ['G', 'fg4a', 'll'], ['G', 'fg4al', 'l'], ['Gf', 'g', '4all'], ['Gf', 'g4', 'all'], ['Gf', 'g4a', 'll'], ['Gf', 'g4al', 'l'], ['Gfg', '4', 'all'], ['Gfg', '4a', 'll'], ['Gfg', '4al', 'l'], ['Gfg4', 'a', 'll'], ['Gfg4', 'al', 'l'], ['Gfg4a', 'l', 'l']]
Time Complexity: O(n2)
Space Complexity: O(n)
Approach#3: Using lambda
This approach uses a recursive approach with an anonymous function (lambda) to generate all possible slices of a string for a given number of slices.
Algorithm
1. The lambda function takes two parameters, the string to be sliced, and the number of slices required.
2. If the required number of slices is greater than 1, the function recursively generates all possible slices of the substring of the input string, starting from index i=1, and constructs a new list with the current slice added at the beginning.
3. The recursion continues until the number of required slices becomes 1, in which case the current slice is the only slice required, and it is returned as a list.
4. The final output is a list of all possible slices.
Python3
test_str = "Gfg4all"
K = 3
slices = lambda s, k: [[s[:i]] + j for i in range ( 1 , len (s)) for j in slices(s[i:], k - 1 )] if k > 1 else [[s]]
print (slices(test_str, K))
|
Output
[['G', 'f', 'g4all'], ['G', 'fg', '4all'], ['G', 'fg4', 'all'], ['G', 'fg4a', 'll'], ['G', 'fg4al', 'l'], ['Gf', 'g', '4all'], ['Gf', 'g4', 'all'], ['Gf', 'g4a', 'll'], ['Gf', 'g4al', 'l'], ['Gfg', '4', 'all'], ['Gfg', '4a', 'll'], ['Gfg', '4al', 'l'], ['Gfg4', 'a', 'll'], ['Gfg4', 'al', 'l'], ['Gfg4a', 'l', 'l']]
Time Complexity: O(n^k), where n is the length of the input string, and k is the number of slices required. This is because the code generates all possible combinations of k slices, each of which can have a maximum length of n.
Space Complexity: O(n^k), as the number of possible combinations is the same as the number of elements in the output list. This can be a significant limitation for large values of k, as it can cause the program to run out of memory.
Similar Reads
Python program to convert String to K sized Numerical Rows
Given a string of alphabets, convert it to K sized numerical rows, which contain the number being the positional value of characters. Input : test_str = 'geeksforgeek', K = 4 Output : [[6, 4, 4, 10], [18, 5, 14, 17], [6, 4, 4, 10]] Explanation : g is at 6th position in alphabet hence gâ 6 and the st
5 min read
Python program to remove last N characters from a string
In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions. Using String SlicingString slicing is one of the simplest and mo
2 min read
Python - Number of positions where Substrings Match of Length K
Given 2 Strings, count positions where substrings of Length K Match. Input : test_str1 = 'geeksforgeeks', test_str2 = 'peeksformeeks', K = 4 Output : 4 Explanation : 4 positions match K length Substrings. Input : test_str1 = 'geeksforgeeks', test_str2 = 'peeksformeeks', K = 5 Output : 3 Explanation
4 min read
Python program to find the character position of Kth word from a list of strings
Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings. Examples: Input : test_list = ["geekforgeeks", "is", "best", "for", "geeks"], K = 21 Output : 0Explanation : 21st index occurs in "geeks" and point to "g
3 min read
Python program to find the occurrence of substring in the string
Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
4 min read
Python program to find Indices of Overlapping Substrings
To count the number of overlapping sub-strings in Python we can use the Re module. To get the indices we will use the re.finditer() method. But it returns the count of non-overlapping indices only. Examples: Input: String: "geeksforgeeksforgeeks" ; Pattern: "geeksforgeeks" Output: [0, 8] Explanation
4 min read
Python | Get the starting index for all occurrences of given substring
Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in #
3 min read
Python program to find product of given number of consecutive elements
Given a List, the task is to write a python program that can construct a list with products of consecutive elements for a given number of elements. Input : test_list = [5, 6, 2, 1, 7, 5, 3], K = 3 Output : [60, 12, 14, 35, 105] Explanation : 5 * 6 * 2 = 60, 6 * 2 * 1 = 12.. And so on. Input : test_l
3 min read
Python - Find all combinations of overlapping substrings of a string
Given a string, the task is to write a Python program to find all combinations of overlapping substrings of a string and store it in a list. The list of lists will be ordered and grouped by length of substrings. Input : test_str = 'Geeks4G' Output : [['', '', '', '', '', '', '', ''], ['G', 'e', 'e',
2 min read
Get the Smallest Window in a String Containing all Characters of Given Pattern - Python
Our task is to find the smallest substring in a given string that contains all the characters of a given pattern. In other words, we are given two strings: one is the main string and the other is the pattern. We need to locate the smallest window in the main string which includes every character fro
3 min read