5 Questions for TYL on Strings(permutations)
1. Write a program to find a Permutation of a given
string (Printing various combinations of
characters in the string)
Constraint : use string inbuilt function
Okay, so last semester, I've seen students struggling with this during Java TYL and this is never covered during the class so it makes it very difficult.
So what is a permutation?
A permutation, also called an "arrangement number" or "order," is a rearrangement of the elements of an ordered list(https://mathworld.wolfram.com/Permutation.html)
So if you have s= "ABC", the permutation would be
ABC
ACB
BAC
BCA
CAB
CBA
Number of resultant strings are 3! = 6
And lexicographic order is nothing but dictionary order... eg. put BAC before BCA...
So the basic algorithm for this would be:
Remove each element from the
n elements one at a time, then append it to the (n-1)! remaining permutations. (https://www.topcoder.com/generating-permutations/)When we do this recursively...
Notice
ABC ACB - A is fixed
BAC BCA - B is fixed
CAB CBA - C is fixed.
So we write one swap for n iterations to bring each character to the front.
for the remaining letters, however many, we swap, reduce, swap until we've reached the end so
if in the first iteration we're going from k to n-1, where k=0, n-1 =2
we increment k by 1,
stop when k=n-1
once we have generated all the strings with the first fixed character, we swap back to original string then restart the process.
A B C
/ | \
/ | \
/ | \
A is fixed, ABC B is fixed, BAC C is fixed, CBA
(k=0, i=0, swap) (k=1, i=0, swap) (k=2, i=0 swap
/ \ / \ / \
/ \ / \ / \
(k=1, i=1, swap) (k=1, i=2, swap) / \ / \
ABC ACB BAC BCA CBA CAB
k=2
k=n-1, stop
The program will look like this:
def permutation(a,n,k=0):
if k == n-1:
print("".join(a))
return;
for i in range(k,n):
a[k], a[i] = a[i],a[k]
permutation(a,n,k+1)
a[k], a[i] = a[i],a[k]
s="ABC"
permutation(list(s),len(s))
ABC
ACB
BAC
BCA
CBA
CAB
Other things that I've not taught yet in class...
In def permutation(a,n,k=0):k=0 is the default value if we're not passing anything during the function call.
We're using "".join(a) to essentially convert a list to a printable string.The method is invoked on the separator... we're using as an empty string so it appends all items together... try these out:
>>> a=['A','B','C']
>>> ':'.join(a)
'A:B:C'
>>> ''.join(a)
'ABC'
>>>
There are other alternate methods... you can look those up here:https://www.topcoder.com/generating-permutations/
If you can remember some packages, the itertools package gives you a permutation function and if you're allowed to use it, then you can write the following code also. The output is lexicographically ordered also.
Alternate program using itertools
import itertools as it
s="ABC"
ps = list(it.permutations(s))
for item in ps:
print("".join(item))
Output:
ABC
ACB
BAC
BCA
CAB
CBA
Comments
Post a Comment