
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Index Ranks of Elements
When it is required to determine the index rank of elements in a data structure, a method is defined that takes a list as a parameter. It iteeates over the elements in the list, and performs certain comparisons before changing the values of two variables.
Example
Below is a demonstration of the same
def find_rank_elem(my_list): my_result = [0 for x in range(len(my_list))] for elem in range(len(my_list)): (r, s) = (1, 1) for j in range(len(my_list)): if j != elem and my_list[j] < my_list[elem]: r += 1 if j != elem and my_list[j] == my_list[elem]: s += 1 my_result[elem] = r + (s - 1) / 2 return my_result my_list = [1, 3, 5, 3, 1, 26, 99, 45, 67, 12] print("The list is :") print(my_list) print("The resultant list is :") print(find_rank_elem(my_list))
Output
The list is : [1, 3, 5, 3, 1, 26, 99, 45, 67, 12] The resultant list is : [1, 3, 5, 3, 1, 7, 10, 8, 9, 6]
Explanation
A method named ‘find_rank_elem’ is defined that takes a list as a parameter.
The list is iterated over and stored in a list variable.
It is again iterated over, and checked to see if certain elements of the list match.
If they do, two values ‘r’ and ‘s’ are changed.
This list is returned as output.
Outside the method, a list is defined and is displayed on the console.
The method is called by passing this list as a parameter.
The output is displayed on the console.