We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def interQuartile(values, freqs):
# Create the data set S
S = []
for i in range(len(values)):
S += [values[i]] * freqs[i]
S = sorted(S)
n = len(S)
def median(sub_arr):
sub_n = len(sub_arr)
mid = sub_n // 2
if sub_n % 2 == 0:
return (sub_arr[mid - 1] + sub_arr[mid]) / 2.0
else:
return sub_arr[mid]
# Calculate Q1
lower_half = S[:n // 2]
Q1 = median(lower_half)
# Calculate Q3
if n % 2 == 0:
upper_half = S[n // 2:]
else:
upper_half = S[(n // 2) + 1:]
Q3 = median(upper_half)
# Print the interquartile range to 1 decimal place
print(f"{Q3 - Q1:.1f}")
if name == 'main':
n = int(input().strip())
values = list(map(int, input().rstrip().split()))
freqs = list(map(int, input().rstrip().split()))
# Ensure that the number of elements in S is equal to the sum of freqs
assert len(values) == len(freqs), "The length of values and freqs must be the same"
assert sum(freqs) <= 1000, "The sum of frequencies must be less than or equal to 1000"
interQuartile(values, freqs)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 1: Interquartile Range
You are viewing a single comment's thread. Return to all comments →
def interQuartile(values, freqs): # Create the data set S S = [] for i in range(len(values)): S += [values[i]] * freqs[i]
if name == 'main': n = int(input().strip()) values = list(map(int, input().rstrip().split())) freqs = list(map(int, input().rstrip().split()))