Create a programming task related to algorithms and data structures,…
- User
Assistant: User: Create a programming task related to algorithms and data structures, similar to LeetCode tasks. Follow this scenario:
Task description: should involve processing a dataset (e.g., an array of numbers) where a specific statistical measure (average, median, mode, etc.) needs to be calculated. Input: A collection of numerical values. Output: A statistical measure calculated from the collection. Provide several examples of input and expected output with explanations. Propose a function with a typical signature that will solve the task.Assistant:
- Assistant
Certainly! Here's a programming task related to processing an array of numbers to calculate a specific statistical measure:
Task: Calculate the Median of an Array
Description:
You are given an array of numerical values, and you need to calculate the median of these numbers. The median is the value separating the higher half from the lower half of a data sample. If the size of the dataset is odd, the median is the middle value. If the size is even, the median is the average of the two middle numbers.Input:
A list of integers,nums[], which can be of lengthnwhere 1 ≤ n ≤ 10^5.Output:
A single float or integer value representing the median of the input numbers.Function Signature:
def calculate_median(nums: List[int]) -> Union[int, float]: passExamples
Example 1:
- Input:
nums = [2, 1, 5, 7, 2, 0, 5] - Output:
2 - Explanation: Sorting the array gives
[0, 1, 2, 2, 5, 5, 7]. The median (middle element) is 2.
Example 2:
- Input:
nums = [3, 1, 4, 1, 5, 9] - Output:
2.5 - Explanation: Sorting the array gives
[1, 1, 3, 4, 5, 9]. The median is the average of the two middle numbers (3 and 4), so (3 + 4) / 2 = 3.5.
Example 3:
- Input:
nums = [1, 1, 1, 1] - Output:
1 - Explanation: The array is already sorted as
[1, 1, 1, 1]. The median is the average of the two middle numbers (1 and 1), so (1 + 1) / 2 = 1.
Constraints
- The values in
numsare not necessarily unique. - The function should handle both odd and even-length arrays efficiently.
- Aim for a time complexity of O(n log n) due to sorting.
Solution Outline
To find the median:
- Sort the array.
- Check if the length of the array is odd or even.
- If odd, return the middle element.
- If even, return the average of the two middle elements.
- Ensure the result is returned in the simplest form possible (as a float when necessary or as an integer).
Use this task, examples, and outline for testing and execution in environments similar to coding platforms or competitive programming sites.
- Input: