Python Program to Replace each element by its Rank in the given Array

Replace each element by its Rank in the given Array

In this article, we will learn about Python Program to Replace each element by its Rank in the given Array through the python program. Given an array of distinct integers, we need to replace each element of the array with its rank. The minimum value element will have the highest rank in the Array.

Example:

Input: [ 10, 8, 15, 12, 6, 20, 1 ]

Output: [ 4, 3, 6, 5, 2, 7, 1 ]

Replace each element of the array by its rank in the array in Python

Keypoint

In this section we will learn about basic knowledge which we need to know before coding the above Program. So we must have knowledge of what is an array? 

What is an array?
An array is a data structure, it is collection of similar data elements which is stored at contiguous memory locations in which each data element can be accessed directly by only using its index number.
 
About Python language:-
Python is a popular programming language. Python is a high level language that will make a programmer focus on what to do instead of how to do.
Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale 
 
 
How to declare an array?
To declare an array in C,a programmer specifies the type of the elements and the number of elements required by an array as follows − This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balanceof type double, use this statement − Here balanceis a variable array which is sufficient to hold up to 10 double numbers

.

Algorithm :

  • Take array of elements as an input from the user
  • Sort the input array and store it in another variable
  • Take an empty list say resultList
  • Traverse each element of input array and find the index of that element in the sorted array
  • Add 1 to the index of the element in sorted array and then append it to the resultList
  • Print resultList
Replace each element of the array by its rank in the array in Python

Code of Python Program to Replace each element by its Rank in the given Array

# Python3 program to Replace each

# element by its Rank in the given Array

# Input array

arr= [ 10, 15, 9, 6, 1, 7, 3, 20 ]

# Sort the input array and store it in another list

a=sorted(arr)

# Result list having ranks

res=[]


# Traverse each element of input array and

# and find rank by fetchind index of the element

# in the soredet list + 1

for i in arr:

res.append(a.index(i)+1)

# Print the resultant list

print(res)
Output :

[6, 7, 5, 3, 1, 4, 2, 8]