Introduction to Sets Python Hackerrank Solution

0

 A set is an unordered collection of elements without duplicate entries. When printed, iterated or converted into a sequence, its elements will appear in an arbitrary order.

Basically, sets are used for membership testing and eliminating duplicate entries.

Task

Now, let's use our knowledge of sets and help Mickey.

Ms. Gabriel Williams is a botany professor at District College. One day, she asked her student Mickey to compute the average of all the plants with distinct heights in her greenhouse.

Formula used:

Average = sum of Distinct Heights/Total Number of Distinct Heights

Function Description

Complete the average function in the editor below.

average has the following parameters:

  • int arr: an array of integers

Returns

  • float: the resulting float value rounded to 3 places after the decimal

Input Format

The first line contains the integer, N the size of arr

The second line contains the N space-separated integer, arr[i].

Sample input 


    STDIN                                                                          Function
    -----                                                                          --------
    10                                                                                  arr[] size N = 10
    161 182 161 154 176 170 167 171 170 174         arr = [161, 181, ..., 174]

Sample Output 


    169.375

Explanation

Here, set ([154, 161, 167, 170, 171, 174, 176, 182]0 is the set containing the distinct heights. Using the sum() and len() functions, we can compute the average.

Average = 1355/8 = 169.375

Introduction to Sets Python Solution 


    def average(array):

            sum_array = sum(set(array))
            len_array = len(set(array))
            output = sum_array/len_array
            return output;

    if __name__ == '__main__':
            n = int(input())
            arr = list(map(int, input().split()))
            result = average(arr)
            print(result)



Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !