Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Have a look at the following pseudocode (Python 3.2):

def anagrams( string ):

    for c in string:

      anagram = c + anagram( string - {c} ) # remove the char from its position in the string

      print(anagram)

    return

def main():

    word = "abcd"

    anagrams( word )

    return

I also need to know a pythonic way to do this process:

anagram = c + anagram( string - {c} )

I don't know how to remove that char from the following string?

"abc" -> 'a' + "bc" -> 'a' + 'b' + "c" -> 'a' + 'b' + 'c' = 'abc'

             + "cb" -> 'a' + 'c' + "b" -> 'a' + 'c' + 'b' = 'acb'

      -> 'b' + "ac" -> 'b' + 'a' + "c" -> 'b' + 'a' + 'c' = 'bac'

             + "ca" -> 'b' + 'c' + "a" -> 'b' + 'c' + 'a' = 'bca'

      -> 'c' + "ba" -> 'c' + 'b' + "a" -> 'c' + 'b' + 'a' = 'cba'

             + "ab" -> 'c' + 'a' + "b" -> 'c' + 'a' + 'b' = 'cab'

1 Answer

0 votes
by (26.4k points)

Why can't you use itertools?

>>> import itertools

>>> ["".join(perm) for perm in itertools.permutations("abc")]

['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

Without itertools:

def all_perms(elements):

    if len(elements) <=1:

        yield elements

    else:

        for perm in all_perms(elements[1:]):

            for i in range(len(elements)):

                yield perm[:i] + elements[0:1] + perm[i:]

word = "abc"

print list(all_perms(word))

Without itertools and without generators:

def all_perms(elements):

    if len(elements) <=1:

        return elements

    else:

        tmp = []

        for perm in all_perms(elements[1:]):

            for i in range(len(elements)):

                tmp.append(perm[:i] + elements[0:1] + perm[i:])

        return tmp

Output:

['abc', 'bac', 'bca', 'acb', 'cab', 'cba']  

Come and Join our python course, to learn python in detail.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...