A dataset consisting of N items. Each item is a pair of a word and a boolean denoting whether the given word is a spam word or not.
There shouldn't be a word included in the training set that's marked both as spam and not-spam. For example item {"fck", 1}
, and item {"fck, 0"}
can't be present in the training set, because first item says the word "fck"
is a spam, whereas the second item says it is not, which is a contradiction.
Your task is to select the maximum number of items in the training set.
Note that same pair of {word, bool}
can appear multiple times in input. The training set can also contain the same pair multiple times.
Question link is here.
What I have done so far:
- Grouped given pair by word and taken count of spam and not-spam of each group.
- Finally, taken
max
count of each group and takensum
of this values.
Code:
from itertools import groupby
from collections import Counter
t = int(input())
for _ in range(t):
n = int(input())
data_set = sorted([tuple(map(str, input().split())) for __ in range(n)])
print(sum(max(Counter(element[1]).values()) for element in groupby(data_set, key=lambda x:x[0])))
My code is working fine. Is my solution is efficient? If not please explain an efficient algorithm.
What is the time complexity of my algorithm?
Is it O(N)
?
Example Input:
3
3
abc 0
abc 1
efg 1
7
fck 1
fck 0
fck 1
body 0
body 0
body 0
ram 0
5
vv 1
vv 0
vv 0
vv 1
vv 1
Example Output:
2
6
3
Constraints:
- 1≤T≤10
- 1≤N≤25,000
- 1≤|wi|≤5 for each valid i
- 0≤si≤1 for each valid i
- w1,w2,…,wN contain only lowercase English letters
Edit-1:
To take input from file for testing,
with open('file.txt', 'r') as f:
for _ in range(int(f.readline())):
n = int(f.readline())
data_set = [tuple(map(str, f.readline().replace('\n','').split())) for __ in range(n)]
print(data_set)
# your logic here
# Output:
# [('abc', '0'), ('abc', '1'), ('efg', '1')]
# [('fck', '1'), ('fck', '0'), ('fck', '1'), ('body', '0'), ('body', '0'), ('body', '0'), ('ram', '0')]
# [('vv', '1'), ('vv', '0'), ('vv', '0'), ('vv', '1'), ('vv', '1')]