Computer >> Computer tutorials >  >> Programming >> Python

Program to find expected number of shuffle required to sort the elements of an array in Python


Suppose we have a set of elements nums. We have to sort them in non-decreasing sequence. But the sorting technique is randomized. We will check whether the array is sorted or not, if not then random shuffle it and check again. Until all the elements are sorted continue this process. In this case we have to find expected number of shuffles required to sort them. Show the answer up to 6 decimal places.

So, if the input is like nums = [5,2,7], then the output will be 6 because there are 3 permutations are possible, so the probability is 1/3

  • If we get sorted array at i = 1 number of iteration, then it will take 1/3
  • If we get sorted array at i = 2 number of iterations, then it will take (2/3)*(1/3)

If we get sorted array at i-th number of iterations, then it will take (2/3)^(i-1) * (1/3)

To solve this, we will follow these steps −

  • if nums is sorted, then
    • return 0
  • otherwise,
    • m:= a new dictionary initially empty
    • for each i in nums, do
      • if i is present in m, then
        • m[i] := m[i] + 1
      • otherwise,
        • m[i]:= 1
    • num:= 1
    • for each key i in m, do
      • num := num * factorial(m[i])
    • den:= factorial(size of nums)
    • return (den/num) and rounding off up to 6 decimal places

Example

Let us see the following implementation to get better understanding −

from math import factorial
def solve(nums):
   if nums == sorted(nums):
      return 0
   else:
      m={}
      for i in nums:
         if i in m:
            m[i]+=1
         else:
            m[i]=1
      num=1
      for i in m:
         num *= factorial(m[i])

      den=factorial(len(nums))
      return round((den/num),6)

nums = [5,2,7]
print(solve(nums))

Input

[5,2,7]

Output

6.0