📜  门| GATE-CS-2014-(Set-3) |问题 16(1)

📅  最后修改于: 2023-12-03 14:58:29.558000             🧑  作者: Mango

Gate-CS-2014-(Set-3) | Question 16

This is a programming question from the Computer Science Graduate Aptitude Test in Engineering (GATE) 2014 - Set 3. The question involves implementing a function in Python that extracts a specified number of elements from a sorted list and returns their average.

Problem Statement

The function has the following signature:

def average_of_elements(arr: list, n: int, k: int) -> float:

The arr parameter is a sorted list of integers and n is the length of that list. The k parameter is an integer that specifies the number of elements to be considered. The function should return the average of these k elements. If k is greater than n, the function should return -1.

Here is an example:

arr = [1, 2, 3, 4, 5]
n = 5
k = 3
assert average_of_elements(arr, n, k) == 3

In this example, the function extracts the first k elements from the sorted list arr, which are [1, 2, 3], and returns their average, which is 3.

Approach

We can implement this function by simply extracting the first k elements from the sorted list and calculating their average. If k is greater than n, then we return -1.

Here is the Python code for this approach:

def average_of_elements(arr: list, n: int, k: int) -> float:
    if k > n:
        return -1

    return sum(arr[:k]) / k

We start by checking if k is greater than n. If it is, then we return -1 as specified in the problem statement. Otherwise, we extract the first k elements from arr using slicing and then calculate their average using the sum() and / operators. Finally, we return the calculated average.

Conclusion

In this problem, we learned how to extract elements from a sorted list and calculate their average in Python. We used slicing to extract the first k elements and then calculated their average using the sum() and / operator. This approach is simple and runs in linear time.