Write a python program to read n values in single line from user into a tuple. Using the values of tuple, display and count inversion. Count and Display the leader(s) from the tuple elements.
Inversion Count indicates – how far (or close) the tuple elements are far from being sorted in ascending order. If tuple is already sorted then inversion count is 0. If tuple is sorted in reverse order that inversion count is the maximum.
An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader.
Input
5
2 4 5 1 3 #enter this element in single line
Output
Count Inversion (5) - [(2, 1), (4, 1), (4, 3), (5, 1), (5, 3)]
Leader (2) – [5, 3]
def findInversionCount(A):
inversionCount = 0
for i in range(len(A) - 1):
for j in range(i + 1, len(A)):
if A[i] > A[j]:
inversionCount = inversionCount + 1
return inversionCount
if __name__ == '__main__':
A = [2, 4, 5, 1, 3]
print("Inversion count is", findInversionCount(A))
def printLeaders(arr, size):
max_from_right = arr[size-1]
print (max_from_right),
for i in range( size-2, -1, -1):
if max_from_right < arr[i]:
print (arr[i]),
max_from_right = arr[i]
# Driver function
arr = [2, 4, 5, 1, 3]
print("Leader is")
printLeaders(arr, len(arr))
Comments
Leave a comment