
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
N-sized Substrings with K Distinct Characters in Python
When it is required to split ‘N’ sized substrings with ‘K’ distinct characters, it is iterated over, and the ‘set’ method is used to get the different combinations.
Example
Below is a demonstration of the same
my_string = 'Pythonisfun' print("The string is : ") print(my_string) my_substring = 2 my_chars = 2 my_result = [] for idx in range(0, len(my_string) - my_substring + 1): if (len(set(my_string[idx: idx + my_substring])) == my_chars): my_result.append(my_string[idx: idx + my_substring]) print("The resultant string is : ") print(my_result)
Output
The string is : Pythonisfun The resultant string is : ['Py', 'yt', 'th', 'ho', 'on', 'ni', 'is', 'sf', 'fu', 'un']
Explanation
A string is defined and is displayed on the console.
A substring, and the characters are defined.
An empty list is defined.
The string is iterated with respect to the number in substring.
If the length of the unique characters in the string is equal to the characters, it is appended to the empty list.
This is the result which is displayed on the console.
Advertisements