'''
How to rank elements of an integer list based on their sorted order in Python
------------------------------------------------------------------------------
Ranking rules:
--------------
- Lowest value gets rank 1
- Equal values share the same rank
- Rank increases only when encountering a new unique value
'''
from typing import List, Dict
# ------------------------------------------------------------
# Function 1: Print the list
# ------------------------------------------------------------
def print_list(lst: List[int]) -> None:
print(f"List: {lst}")
# ------------------------------------------------------------
# Function 2: Create a copy of the list
# ------------------------------------------------------------
def copy_list(lst: List[int]) -> List[int]:
return lst[:] # shallow copy
# ------------------------------------------------------------
# Function 3: Sort the list copy
# ------------------------------------------------------------
def sort_list(lst_copy: List[int]) -> None:
lst_copy.sort()
# ------------------------------------------------------------
# Function 4: Build a map of value → rank
# ------------------------------------------------------------
def build_rank_map(sorted_lst: List[int]) -> Dict[int, int]:
rank_map: Dict[int, int] = {}
if not sorted_lst:
return rank_map
rank = 1
previous = sorted_lst[0]
rank_map[previous] = rank
for i in range(1, len(sorted_lst)):
if sorted_lst[i] != previous:
rank += 1
rank_map[sorted_lst[i]] = rank
previous = sorted_lst[i]
return rank_map
# ------------------------------------------------------------
# Function 5: Apply ranks to original list order
# ------------------------------------------------------------
def apply_ranks(original: List[int], rank_map: Dict[int, int]) -> List[int]:
ranked = []
for value in original:
ranked.append(rank_map[value])
return ranked
# ------------------------------------------------------------
# Main ranking function
# ------------------------------------------------------------
def rank_list(lst: List[int]) -> None:
print_list(lst)
if lst is None or len(lst) == 0:
return
lst_copy = copy_list(lst)
sort_list(lst_copy)
rank_map = build_rank_map(lst_copy)
ranked = apply_ranks(lst, rank_map)
print(f"Rank: {ranked}")
# ------------------------------------------------------------
# MAIN
# ------------------------------------------------------------
if __name__ == "__main__":
lst = [33, 99, 10, 25, 47, 11, 77]
rank_list(lst)
'''
run:
List: [33, 99, 10, 25, 47, 11, 77]
Rank: [4, 7, 1, 3, 5, 2, 6]
'''