When it is required to find N sized substrings which have K distinct characters, a method is defined that takes three parameters and uses ‘if’ condition to return the required string.
Example
Below is a demonstration of the same
def generate_my_string(string_size, substring_size, distinct_chars): my_string = "" count_1 = 0 count_2 = 0 for i in range (string_size): count_1 += 1 count_2 += 1 if (count_1 <= substring_size): if (count_2 <= distinct_chars): my_string = my_string + chr(96 + count_1) else: my_string = my_string + 'a' else: count_1 = 1 count_2 = 1 my_string = my_string + 'a' return my_string my_string_size = 8 my_substring_size = 6 K_distinct_chars = 4 print("The string size is :") print(my_string_size) print("The substring size is :") print(my_substring_size) print("The distinct characters count is :") print(K_distinct_chars) print("The resultant string is :") print(generate_my_string(my_string_size, my_substring_size, K_distinct_chars))
Output
The string size is : 8 The substring size is : 6 The distinct characters count is : 4 The resultant string is : abcdaaab
Explanation
A method named ‘generate_my_string’ is defined that takes the string size, the substring size and the distinct characters as parameters.
An empty string is defined.
Two integer values are initialized to 0.
The string size is iterated over, and the two integer values are incremented.
If the first integer value is less than or equal to the size of the substring, the character is converted into a different character.
Otherwise, it is concatenated with the letter ‘a’.
Otherwise, the two integer variables are assigned to 1.
This string is returned as output.
Outside the method, the string size, the substring size and the number of distinct characters are defined.
These values are displayed on the console.
The method is called by passing these parameters.
The output is displayed on the console.