• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Lesson 3. FOR cycle

Difficulty level:

Task«Ranks»

💻 Python

You and your friends have organized a small tournament in your favorite video game "Space Rangers". Each of you played one match and recorded the final scores. Now you face the most difficult task — not just finding the winner, but compiling a full ranking of all participants.

The ranking is determined by the following rules:

  1. The player with the highest score gets 1st place (rank 1).
  2. The player with the second highest score gets 2nd place (rank 2), and so on.
  3. If several players have the same score, they all share the same rank. For example, if two players have the maximum score, they both get rank 1. The next player after them gets rank 3 (since the first two places are taken).

Write a program that takes the scores of all players as input and outputs their final ranks in the same order.

Requirements:
Use only basic constructs: input and output, conditional statements (if) and for loops. Try not to use built-in sorting functions or other complex data structures.

Input format

Glasses of players in the tournament (one line containing integers separated by a gap).

Output format

Ranks for each player in the same order (one line containing integers separated by a gap).

Example

Input

100 150 120 150 80

Output

4 1 3 1 5 & nbsp;

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
# Получаем на вход строку с очками, разделенными пробелами
scores_str = input().split()

# Создаем пустой список, в который будем складывать числовые значения очков
scores = []
# С помощью цикла for проходим по каждому элементу в списке строк
for s in scores_str:
    # Преобразуем каждую строку в целое число и добавляем в список scores
    scores.append(int(s))

# Создаем список для будущих рангов, по размеру такой же, как список очков
# Изначально он может быть заполнен любыми значениями, например, нулями
ranks = [0] * len(scores)

# Главный цикл: проходим по каждому очку в списке, чтобы вычислить его ранг
# Переменная 'i' будет индексом текущего игрока
for i in range(len(scores)):
    # Для каждого очка начинаем считать ранг с 1 (самый высокий ранг)
    current_rank = 1
    # Вложенный цикл: сравниваем текущее очко (scores[i]) со всеми остальными в списке
    # Переменная 'j' будет индексом игрока, с которым мы сравниваем
    for j in range(len(scores)):
        # Если мы находим очко (scores[j]), которое строго больше текущего (scores[i])...
        if scores[j] > scores[i]:
            # ...то ранг нашего текущего игрока 'i' становится хуже, поэтому увеличиваем его на 1
            current_rank += 1
    
    # После сравнения со всеми остальными, записываем вычисленный ранг в список рангов
    # на ту же позицию 'i', где находится очко этого игрока
    ranks[i] = current_rank

# Выводим итоговый список рангов
# Проходим циклом по всем элементам списка ranks
for r in ranks:
    # Печатаем каждый ранг, добавляя после него пробел, чтобы все было в одну строку
    print(r, end=' ')

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

AI Helper

Hi! I am your programming assistant. Ask me anything about Python — I can explain functions, methods, and help you understand the current task!