Python program to get all permutations of size r of a string

PythonServer Side ProgrammingProgramming

Suppose we have a string s and a number r. We have to display all permutations of r number of characters in s. We have permutations() function to get all permutations. This function is present inside itertools library.

So, if the input is like s = "HELLO" r = 3, then the output will be

>['HEL', 'HEL', 'HEO', 'HLE', 'HLL', 'HLO', 'HLE', 'HLL', 'HLO', 'HOE', 'HOL', 'HOL', 'EHL', 'EHL', 'EHO', 'ELH', 'ELL',
'ELO', 'ELH', 'ELL','ELO', 'EOH', 'EOL', 'EOL', 'LHE', 'LHL', 'LHO', 'LEH', 'LEL', 'LEO', 'LLH', 'LLE', 'LLO', 'LOH', 'LOE',
'LOL', 'LHE', 'LHL', 'LHO', 'LEH', 'LEL', 'LEO', 'LLH', 'LLE', 'LLO', 'LOH', 'LOE', 'LOL', 'OHE', 'OHL', 'OHL', 'OEH', 'OEL',
'OEL', 'OLH', 'OLE', 'OLL', 'OLH', 'OLE', 'OLL']

To solve this, we will follow these steps −

  • vals:= a list with all permutations of size r from s
  • res:= a new list
  • for each x in vals, do
    • convert list of characters x into string and insert into res
  • return res

Example

Let us see the following implementation to get better understanding

from itertools import permutations
   def solve(s, r):
   vals=list(permutations(s,r))
   res=[]
   for x in vals:
      res.append(''.join(x))
   return res

s = "HELLO"
r = 3
print(solve(s, r))

Input

"HELLO", 2

Output

['HEL', 'HEL', 'HEO', 'HLE', 'HLL', 'HLO', 'HLE', 'HLL', 'HLO', 'HOE',
'HOL', 'HOL', 'EHL', 'EHL', 'EHO', 'ELH', 'ELL', 'ELO', 'ELH', 'ELL', 'ELO',
'EOH', 'EOL', 'EOL', 'LHE', 'LHL', 'LHO', 'LEH', 'LEL', 'LEO', 'LLH', 'LLE',
'LLO', 'LOH', 'LOE', 'LOL', 'LHE', 'LHL', 'LHO', 'LEH', 'LEL', 'LEO', 'LLH',
'LLE', 'LLO', 'LOH', 'LOE', 'LOL', 'OHE', 'OHL', 'OHL', 'OEH', 'OEL', 'OEL',
'OLH', 'OLE', 'OLL', 'OLH', 'OLE', 'OLL']
raja
Published on 12-Oct-2021 07:02:00
Advertisements