def gettype(line):
    return line[-1]
S1, S2 = 0, 0
with open(path) as f:
    lines = f.read().splitlines()
lines.sort(key=gettype)
for type, group in itertools.groupby(lines, gettype):
    ids = (line.partition(' ')[0] for line in group)
if type == '1' or type == '2':
    S1 += len(set(ids))
elif type == '3' or type == '4':
    S2 += len(set(ids))
else:
    assert 0, (type, list(ids))
print(S1, S2)
How to improve performance of this counting program?