Last active
December 2, 2022 09:55
-
-
Save sharno/9562e8f99761f41817daf522279635cb to your computer and use it in GitHub Desktop.
hackerearth: Sum as per frequency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
# Sample code to perform I/O: | |
name = input() # Reading input from STDIN | |
print('Hi, %s.' % name) # Writing output to STDOUT | |
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail | |
''' | |
# Write your code here | |
N = int(input()) | |
xs = input() | |
xs = [int(x) for x in xs.split()] | |
Q = int(input()) | |
qs = [] | |
for i in range(Q): | |
q = input() | |
[l, r] = q.split() | |
qs.append((int(l), int(r))) | |
# number to frequency dictionary | |
nf = {} | |
for x in xs: | |
f = nf.get(x, 0) | |
nf[x] = f + 1 | |
# frequency to sum of numbers of the same frequency dictionary | |
fn = {} | |
for k,v in nf.items(): | |
ns = fn.get(v, 0) | |
fn[v] = ns + k*v | |
# list with its index as the frequency and the value as the sum of numbers of this frequency | |
fs = [] | |
for i in range(max(fn.keys()) + 1): | |
fs.append(fn.get(i, 0)) | |
# solution | |
for (l, r) in qs: | |
print(sum(fs[l:r+1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
``s index as the frequency and the value a