• Предмет: Информатика
  • Автор: vorizonbusiness
  • Вопрос задан 4 месяца назад

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].

Ответы

Ответ дал: mixail0809
0

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]

Ответ дал: PPPOPOCHE
0

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.

Вас заинтересует