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

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


Let us see the following implementation to get better understanding

from itertools import permutations
   def solve(s, r):
   for x in vals:
   return res

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


"HELLO", 2


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