You have an array of number like
[1,3,4,6,8] we need to find that these numbers are permutation of number or not, considering all numbers in an array.
input : [1,3,4,5,7] output: this is not a permutation. input : [1,2,3,4,5] output : this is a permutation. input : [1,2,3,4,5,7] output: this is not a permutation.
Permutation of 4 is
4! = 4*3*2*1. As we can see in the permutation of 4 we have all numbers 1 to 4. So first condition is:
- Array should contain all number means for
1 to nnumbers
As you can see in 4! it consist of 1 to 4 means array length should me equal to 4. Now second condition is:
- Array length should me same as max of array, means if array max is
nthen length should me
- Array should not contain duplicate numbers.
If you observe the array which has permutation of number, if we sort them ascending order and descending order then sum both array number then we will get same number. let see with example.
input array : [1,3,5,4,2] sorted_1 = [1,2,3,4,5] sorted_2 = [5,4,3,2,1] sorted_1 + sorted_2 = [6,6,6,6,6]
As you can see in above example if we sum ascending and descending sorted array we are getting same for each number of sum.
def isPermutation(arr): # Omit duplicate element of array using set and sorting it. sortedNum = sorted(set(arr)) # First check max of arr is same as length of array if(len(arr) < sortedNum[-1]): print('No permutation') return # doing sum of ascending and descending array/ numSum = list(map(lambda a, b: a+b, sortedNum, sortedNum[::-1])) result = numSum.count(numSum) == len(numSum) if(result): print('array has Number with permutation') else: print('No permutation')
In above code we can omit extra step our code can be like this.
def isPermutation(arr): # Omit duplicate element of array using set and sorting it. sortedNum = sorted(set(arr)) # First check max of arr is same as length of array if(len(arr) < sortedNum[-1]): print('No permutation') return else: print('yes, permutation')