Files
tira/viikko5/mode.py
T
2023-11-07 01:27:43 +02:00

44 lines
1010 B
Python

class Mode:
def __init__(self):
self.dict = {}
self.mode = 0
self.count = 0
def add(self, x):
if self.dict.get(x) is None:
self.dict[x] = 1
else:
self.dict[x] += 1
if self.dict[x] > self.count:
self.mode = x
self.count = self.dict[x]
return self.mode
elif self.dict[x] == self.count:
self.mode = x if x < self.mode else self.mode
return self.mode
return self.mode
if __name__ == "__main__":
m = Mode()
print(m.add(1)) # 1
print(m.add(2)) # 1
print(m.add(2)) # 2
print(m.add(1)) # 1
print(m.add(3)) # 1
print(m.add(3)) # 1
print(m.add(3)) # 3
m = Mode()
print(m.add(500000000))
print(m.add(500000008))
print(m.add(500000002))
print(m.add(500000004))
print(m.add(500000005))
print(m.add(500000001))
print(m.add(500000003))
print(m.add(500000001))
print(m.add(500000005))