HackerRank Python: Introduction to Sets Solution

Question

Solution

				
					def average(array):
    s=set(array)
    return sum(s)/len(s)

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

This code defines a function named average that calculates the average of a given array of numbers. Here’s a step-by-step explanation of the code:

  1. The function average takes an array as input.
  2. It creates a set s from the array by using the set() function. This eliminates any duplicate values in the array, as sets only store unique elements.
  3. The sum of the elements in the set s is calculated using the sum() function.
  4. The length of the set s is calculated using the len() function.
  5. The sum of the elements is divided by the length of the set to obtain the average.
  6. The average value is then returned by the function.

The code also includes a block that executes when the script is run directly (not imported as a module):

  1. It prompts the user to enter an integer n using the input() function.
  2. It reads a line of space-separated numbers from the user and converts them into a list of integers using the map() and split() functions.
  3. The average function is called with the obtained list as an argument, and the result is assigned to the variable result.
  4. Finally, the calculated average is printed to the console using the print() function.

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment