hello dear coders, So today we came with a really interesting project.
This project will be the practice of your logical skills and it will clear all your concepts of while loops and function. So we all might come across the problem of dictionary word ranking in permutations and combinations in our high schools so here is code to find the rank of certain words. For this, you should have a little knowledge of the factorial of a number (!) so let's start:
The code goes like this:
# Python program to find lexicographic
# rank of a string
# A utility function to find factorial
# of n
def fact(n) :
f = 1
while n >= 1 :
f = f * n
n = n - 1
return f
# A utility function to count smaller
# characters on right of arr[low]
def findSmallerInRight(st, low, high) :
countRight = 0
i = low + 1
while i <= high :
if st[i] < st[low] :
countRight = countRight + 1
i = i + 1
return countRight
# A function to find rank of a string
# in all permutations of characters
def findRank (st) :
ln = len(st)
mul = fact(ln)
rank = 1
i = 0
while i < ln :
mul = mul / (ln - i)
# count number of chars smaller
# than str[i] fron str[i + 1] to
# str[len-1]
countRight = findSmallerInRight(st, i, ln-1)
rank = rank + countRight * mul
i = i + 1
return rank
# Driver program to test above function
st = "ranker"
print (findRank(st))
if you face any doubts feel free to comment down your query.