Python - Character repetition string combinations

PythonServer Side ProgrammingProgramming

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.

raja
Updated on 21-Sep-2021 07:56:15

Advertisements