Python Program to get all Possible Slices of a String for K Number of Slices

Getting all possible slices of a string for K number of slices means dividing a string into exactly K parts in all possible ways. Python provides multiple approaches to solve this problem: iteration and using itertools.combinations.

Method 1: Using Iterative Approach

This method builds slices iteratively by extending existing slices from previous iterations ?

def get_all_slices_iteration(string, k):
    slices = [[]]
    
    for i in range(k):
        new_slices = []
        for slice_list in slices:
            remaining_length = len(string) - sum(map(len, slice_list))
            for j in range(1, remaining_length + 1):
                new_slices.append(slice_list + [string[:j]])
        slices = new_slices
    
    return slices

# Example
input_string = "welcome"
num_slices = 3
result = get_all_slices_iteration(input_string, num_slices)

print(f"Total slices found: {len(result)}")
print("First 5 slice combinations:")
for i, slice_list in enumerate(result[:5]):
    print(f"{i+1}: {slice_list}")
Total slices found: 35
First 5 slice combinations:
1: ['w', 'w', 'w']
2: ['w', 'w', 'we']
3: ['w', 'w', 'wel']
4: ['w', 'w', 'welc']
5: ['w', 'w', 'welco']

How It Works

The algorithm starts with an empty slice list and iteratively builds K slices:

  • Calculate remaining string length after existing slices
  • Generate all possible lengths for the next slice
  • Create new combinations by extending existing slices

Method 2: Using itertools.combinations

This approach uses combinations to select cutting points in the string ?

import itertools

def get_slices_combinations(string, k):
    slices = []
    # Generate combinations of k-1 cutting points from positions 1 to len-1
    for combo in itertools.combinations(range(1, len(string)), k - 1):
        # Add start and end positions
        indices = [0] + list(combo) + [len(string)]
        # Create slices based on these indices
        slice_list = [string[indices[i]:indices[i + 1]] for i in range(k)]
        slices.append(slice_list)
    
    return slices

# Example
input_string = "welcome"
num_slices = 3
result = get_slices_combinations(input_string, num_slices)

print(f"Total slices found: {len(result)}")
for i, slice_list in enumerate(result):
    print(f"{i+1}: {slice_list}")
Total slices found: 15
1: ['w', 'e', 'lcome']
2: ['w', 'el', 'come']
3: ['w', 'elc', 'ome']
4: ['w', 'elco', 'me']
5: ['w', 'elcom', 'e']
6: ['we', 'l', 'come']
7: ['we', 'lc', 'ome']
8: ['we', 'lco', 'me']
9: ['we', 'lcom', 'e']
10: ['wel', 'c', 'ome']
11: ['wel', 'co', 'me']
12: ['wel', 'com', 'e']
13: ['welc', 'o', 'me']
14: ['welc', 'om', 'e']
15: ['welco', 'm', 'e']

How It Works

This method selects K-1 cutting positions from the string and creates slices:

  • Choose K-1 positions from 1 to string length-1
  • Add position 0 (start) and string length (end)
  • Create slices using these positions as boundaries

Comparison

Method Approach Results Best For
Iterative Builds slices step by step All possible slice combinations When you need all variations
itertools.combinations Selects cutting points Unique string divisions Distinct ways to divide string

Conclusion

The iterative approach generates all possible slice combinations, while itertools.combinations creates distinct ways to divide the string. Choose the iterative method for comprehensive results or combinations for unique divisions.

---
Updated on: 2026-03-27T13:49:56+05:30

193 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements