Harsha Raj
Harsha Raj

Reputation: 11

How to print all permutations of a string

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.

Upvotes: 0

Views: 103

Answers (3)

Shounak Das
Shounak Das

Reputation: 368

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)

Upvotes: 0

Talha Tayyab
Talha Tayyab

Reputation: 27317

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']

Upvotes: 1

Daniel Hao
Daniel Hao

Reputation: 4980

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']

Upvotes: 1

Related Questions