Movatterモバイル変換


[0]ホーム

URL:


Open In App

The task is to generate all the possible permutations of a given string. A permutation of a string is a rearrangement of its characters. For example, the permutations of "ABC" are "ABC", "ACB", "BAC", "BCA", "CAB", and "CBA". The number of permutations of a string with n unique characters is n! (factorial of n).

Using itertools.permutations

itertools module in Python provides a simple function called permutations that can generate all possible permutations of a string. This method is the easiest and most efficient, especially when working with built-in Python libraries.

Python
importitertoolss="GFG"li=[''.join(p)forpinitertools.permutations(s)]print(li)

Explanation:

  • itertools.permutations(s): generates all possible permutations of the string s, returning each permutation as a tuple.
  • ''.join(p): converts each tuple p into a string by concatenating its elements.
  • list comprehension collects all the joined strings (permutations) into a list.

Using Recursion

Recursion repeatedly breaks the problem into smaller parts. In string permutation, it means choosing one character and recursively arranging the remaining characters, generating all possible orderings systematically.

Python
defpermute(s,s2):iflen(s)==0:print(s2,end=' ')returnforiinrange(len(s)):char=s[i]left_s=s[0:i]right_s=s[i+1:]rest=left_s+right_spermute(rest,s2+char)s1="GFG"s2=""permute(s1,s2)

Output
GFG GGF FGG FGG GGF GFG

Explanation:

  • If the string s is empty, print the accumulated answer.
  • For each character in s, remove the character and recursively permute the remaining characters while adding the character to answer.
  • Call permute(s, answer) with the initial string and an empty answer to start generating permutations.

Related Articles:


Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp