Write a Python program to print all permutations of a given string (including duplicates)


The program generates all possible permutations of a given string of numbers using recursion.

  • The program defines a function called permutations that takes a string str_val as input. The function first checks if the length of the input string is 0, and if so, returns a list with a single empty string.
  • If the length of the input string is not 0, the function recursively calls itself with the substring str_val[1:len(str_val)]. This will give a list pre containing all possible permutations of the substring.
  • Next, the function creates an empty list next and iterates over each permutation in pre. For each permutation, the function inserts the first character of the input string at every position in the permutation to generate new permutations, and appends the new permutations to the next list.
  • Finally, the function returns the next list containing all possible permutations of the input string.
  • The program then prompts the user to enter a string of numbers, calls the permutations function with the input string, and prints the resulting list of permutations.

Source Code

def permutations(str_val):
    if len(str_val) == 0:
        return ['']
    pre = permutations(str_val[1:len(str_val)])
    next = []
    for i in range(0,len(pre)):
        for j in range(0,len(str_val)):
            new_str_val = pre[i][0:j]+str_val[0]+pre[i][j:len(str_val)-1]
            if new_str_val not in next:
                next.append(new_str_val)
    return next
 
str_val = input("Enter the Numbers :")
print(permutations(str_val))

Output

Enter the Values :234
['234', '324', '342', '243', '423', '432']

Example Programs