Home > other >  How to print all permutations of a string
How to print all permutations of a string

Time:12-31

Writing a program to print all permutations of a string

def permute(s, answer):
    if (len(s) == 0):
        print(answer, end="  ")
        return
 
    for i in range(len(s)):
        left_substr = s[0:i]
        right_substr = s[i   1:]
        rest = left_substr   right_substr
        permute(rest, answer   ch)
 
answer = ""
 
s = "ABC"
 
print("All possible strings are : ")
permute(s, answer)

I was expecting to get the permutations of string.

CodePudding user response:

Maybe this is what you're looking for:

Note - your program won't run, because the syntax error pointed out earlier. And this will Not use the permutations lib method. (assuming this is some kind of assignment) ;-)


def permute(s):
    if len(s) == 1:
        return [s]
    
    outs = []
    
    for i, ch in enumerate(s):
        outs  = [ch   p for p in permute(s[:i]   s[i 1:])]
    return outs


print(permute('ABC'))
# ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

CodePudding user response:

Since your question is not clear. This is also one of the ways:

from itertools import permutations as p
s="ABC"
for x in range(len(s) 1):
    print(list(p(s,x)))

[()]
[('A',), ('B',), ('C',)]
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]

Link to doc: itertools.permutations

If you are looking for this:

[''.join(y) for y in p(s,3)]
['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

CodePudding user response:

In your code, you have wrote:

left_substr = s[0:i]
right_substr = s[i   1:]
rest = left_substr   right_substr
permute(rest, answer   left_substr)

for permutations of string, left_substr should be s[i] and the rest should be s[0:i] right_subst. It is important to mention that s[0:i] is different from s[i].The first one refers to a slice of the list from index 0 to index i, while s[i] refers to the element at index i. So, your final code should be:

def permute(s, answer):
    if (len(s) == 0):
        print(answer, end="  ")
        return

    for i in range(len(s)):
        left_substr = s[i]
        right_substr = s[i   1:]
        rest = s[0:i]   right_substr
        permute(rest, answer   left_substr)


answer = ""
s = "ABC"
print("All possible strings are : ")
permute(s, answer)
  • Related