Average of Distinct Heights Detailed Version #Python #HackerRank #Sets #AverageCalculation #Detailed

preview_player
Показать описание
In this problem, you are given an array of integers representing the heights of plants. Your task is to compute the average height of the distinct plants, meaning that any duplicate height values should only be counted once. This problem leverages Python sets to remove duplicates and then calculates the average using the sum and length of the resulting set.

Step-by-Step Explanation:

Input Handling:

The first input line contains an integer N, the number of elements in the array.

The second line contains N space-separated integers, each representing a plant’s height.

Using Sets to Remove Duplicates:

A set in Python automatically eliminates duplicate entries. By converting the list of heights to a set, we get only the distinct heights.

Average Calculation:

The average is computed by summing the distinct heights and dividing by the number of distinct heights.

Use the built-in functions sum() and len() on the set to calculate the average.

The result should be rounded or formatted to three decimal places.

Output:

The output is printed on a single line as a float formatted to three decimal places.

This solution demonstrates efficient data processing using Python’s set data structure for duplicate removal and simple arithmetic for average calculation.

Code (Detailed Version):

def average(arr):
# Convert list to set to eliminate duplicates
distinct_heights = set(arr)
# Calculate and return the average of the distinct heights
return sum(distinct_heights) / len(distinct_heights)

def solve():
n = int(input().strip())
arr = list(map(int, input().split()))
# Compute average using the average function and format to 3 decimal places
result = average(arr)
print(format(result, '.3f'))

if __name__ == '__main__':
solve()
Рекомендации по теме
visit shbcf.ru