Skip to content

Instantly share code, notes, and snippets.

@Semant1ka
Last active February 20, 2022 03:11
Show Gist options
  • Save Semant1ka/7a505cfb8b0cfd020425193eb9d16f77 to your computer and use it in GitHub Desktop.
Save Semant1ka/7a505cfb8b0cfd020425193eb9d16f77 to your computer and use it in GitHub Desktop.
Maximum hit count in any given window
"""
You are given a set of log files in the format below.
Write a function that will return a resource with maximum number of hits in any 5 minute time frame.
You should return hits count and resource name.
"""
log = [
["2", "user_1", "resource_1"],
["130", "user_1", "resource_1"],
["355", "user_1", "resource_2"],
["599", "user_1", "resource_1"],
["113", "user_1", "resource_1"],
["897", "user_1", "resource_2"],
["425", "user_1", "resource_2"],
]
from collections import defaultdict
def return_max_hits(log):
log = sorted(log, key=lambda x: int(x[0]))
i, j = 0, 0
counts = defaultdict(int)
max_count, max_resource = 0, ""
# start from each log record
while i < len(log):
time, user, resource = log[i]
time = int(time)
# expand the window until it is less than
# start + 300 or until log ends
while j < len(log):
next_time = int(log[j][0])
if next_time <= time + 300:
counts[log[j][2]] += 1
j += 1
else:
break
res = max(counts, key=counts.get)
cnt = counts[res]
print(f'this iteration max={cnt}, resource = {res} ')
if cnt > max_count:
max_count, max_resource = cnt, res
# if log ended return result, there is no point of narrowing the window
if j == len(log):
return max_count, max_resource
# deduct the start of the window count
# from the counts dictionary and move the
# start to the next log record
counts[resource] -= 1
i += 1
return max_count, max_resource
print(return_max_hits(log))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment