Given a list of integers nums, return the list sorted based on its length:
-
If the length of
nums
is even, return the list sorted in ascending order.
-
If the length of
nums
is odd, return the list sorted in descending order.
For example, [3,1,2] has length 3 (odd), so it should be returned as [3,2,1]. The list [3,1,4,2] has length 4 (even), so it should be returned as [1,2,3,4].
Function Signature
def conditional_sort(nums: list[int]) -> list[int]:
Rules
-
The decision depends only on the length of
nums
, never on the values.
-
Duplicate values are kept, so the output has the same length as the input.
-
An empty list has length 0, which is even, so the result is an empty list.
Constraints
-
0 <= len(nums) <= 10^4
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [3,1,2]
Output: [3,2,1]
The list has length 3 (odd), so it is sorted in descending order.
Input: nums = [3,1,4,2]
Output: [1,2,3,4]
The list has length 4 (even), so it is sorted in ascending order.
Input: nums = [5,-2,5,0,7]
Output: [7,5,5,0,-2]
The list has length 5 (odd), so it is sorted in descending order. Both copies of 5 stay in the result, and the negative value ends up last.