• Write a Python function that takes in a list of integers and returns a new list that contains only the unique elements of the original list, sorted in descending order by the number of times each element appears in the original list. If two or more elements appear the same number of times, they should be sorted in ascending order. For example, given the list [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], the function should return [4, 3, 2, 1].

Ответы 2

  • def unique_sorted_descending(input_list):

       # create a dictionary to store the count of each element

       count_dict = {}

       for num in input_list:

           if num in count_dict:

               count_dict[num] += 1

           else:

               count_dict[num] = 1

       # sort the elements based on count and then by value

       sorted_list = sorted(count_dict.items(), key=lambda x: (-x[1], x[0]))

       # return the sorted list of unique elements

       return [elem[0] for elem in sorted_list]

    • Автор:

      juliaydsf
    • 1 год назад
    • 9
  • This function first creates a dictionary to store the count of each element in the input list. It then uses the sorted function to sort the dictionary items by count (in descending order) and then by value (in ascending order). Finally, it returns a list of the sorted unique elements.

  • Добавить свой ответ

Еще вопросы

Войти через Google

или

Забыли пароль?

У меня нет аккаунта, я хочу Зарегистрироваться

How much to ban the user?
1 hour 1 day 100 years