
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Character repetition string combinations
When it is required to get the character repetitions of a given character, a method is defined that uses the index value to print the repetitions.
Example
Below is a demonstration of the same
def to_string(my_list): return ''.join(my_list) def lex_recurrence(my_string, my_data, last_val, index_val): length = len(my_string) for i in range(length): my_data[index_val] = my_string[i] if index_val==last_val: print(to_string(my_data)) else: lex_recurrence(my_string, my_data, last_val, index_val+1) def all_lex(my_string): length = len(my_string) my_data = [""] * (length+1) my_string = sorted(my_string) lex_recurrence(my_string, my_data, length-1, 0) my_string = "MQ" print("The string is :") print(my_string) print("All permutations with repetition of " + my_string + " are...") all_lex(my_string)
Output
The string is : MQ All permutations with repetition of MQ are... MM MQ QM QQ
Explanation
A method named ‘to_string’ is defined that takes a list as parameter and returns it by joining all values.
Another method named ‘lex_recurrence’ is defined that takes a string, index values as parameter.
It iterates over the length of the string, and checks to see if the last value and the index value are the same.
If they are, it is printed as one of the combination.
Otherwise, the method is called again by incrementing the value of index.
Another method named ‘all_lex’ is defined that sorts the string using the ‘sorted’ method and calls the previous method again.
Outside the method, a string is defined and is displayed on the console.
The output is displayed on the console.
- Related Articles
- How not to match a character after repetition in Python Regex?\n\n
- How to get the combinations for a range of values with repetition in R?
- Element repetition in list in Python
- Python – Index Value repetition in List
- Python – Character indices Mapping in String List
- First Unique Character in a String in Python
- Frequency of each character in String in Python
- Python – Sort String list by K character frequency
- What are regular expression repetition cases in Python?
- Python program for removing nth character from a string
- Removing nth character from a string in Python program
- Count occurrences of a character in string in Python
- Python – Test String in Character List and vice-versa
- Python Program to accept string ending with alphanumeric character
- Python Program to replace the string by specified character
