Tuesday, April 20, 2021

Printing out all the permutations of string

How to generate permutation of a given string where digits are kept as it is, but alphabets are replaced by lower and upper case characters
#! /usr/env/path python
def helper(string, result, index , slate):
if (len(string) == len(slate)):
result.append(slate)
return
if(string[index].isdigit()):
slate = slate + str(string[index])
helper(string, result, index+1, slate)
slate = slate[:-1]
else:
slate= slate + str(string[index].upper());
helper(string, result, index+1, slate)
slate = slate[:-1]
slate = slate + str(string[index].lower())
helper( string, result, index+1, slate)
result =[]
helper("a1b2",result, 0 , "")
print(result)
The above solution uses immutable strings so its not efficient time complexity-wise below solution replaces string with list
#! /usr/env/path python
''' This solution is done using list and removes the immutable
string to avoid extra burden on time '''
def solutions():
result=[]
def helper(index,slate=None):
if slate== None:
slate=[]
if len(slate) == bag_len:
result.append(''.join(slate))
return
if(bag[index].isdigit()):
slate.append(bag[index])
helper(index+1, slate)
slate.pop()
else:
slate.append(str(bag[index].upper()))
helper(index+1,slate)
slate.pop()
slate.append(str(bag[index].lower()))
helper(index+1, slate)
slate.pop()
slate1 = list()
bag = list("a1b2c3")
bag_len = len(bag)
helper( 0, slate1)
print(result)
solutions()
view raw strinnum.py hosted with ❤ by GitHub

No comments:

Post a Comment