Print all permutations of a string in python

Python program for Print all permutations of a string. Here more information.

#  Python 3 program for
#  Print all permutations of a string
class Permutation :
	#  Swapping two string elements by index
	def swap(self, text, size, a, b) :
		#  Check valid location of swap element
		if ((a >= 0 and a < size) and(b >= 0 and b < size)) :
			data = list(text)
			data[a],data[b] = data[b],data[a]
			return ''.join(data)
		return text
	
	#  Method which is print all permutations of given string
	def findPermutation(self, text, n, size) :
		if (n > size) :
			return
		
		if (n == size) :
			print(text)
			return
		
		i = n
		while (i < size) :
			#  Swap the element
			text = self.swap(text, size, i, n)
			self.findPermutation(text, n + 1, size)
			#  Swap the element
			text = self.swap(text, size, i, n)
			i += 1
		
	

def main() :
	task = Permutation()
	text = "ABC"
	size = len(text)
	task.findPermutation(text, 0, size)
	print()
	text = "abcd"
	size = len(text)
	task.findPermutation(text, 0, size)

if __name__ == "__main__": main()

Output

ABC
ACB
BAC
BCA
CBA
CAB

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved