-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
49 lines (37 loc) · 1.11 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from action import Action
from rwlock import RWLock
import json
class Solution(object):
def __init__(self):
self.database = {}
self.lock = RWLock()
def add_action(self, action):
"""
Adds a new action to the database.
:param action: string formatted json object. Ex. '{"action":"jump", "time":100}'
:return: None
"""
action_json = json.loads(action)
action_name = action_json.get('action', '')
action_duration = action_json.get('time', 0)
with self.lock.w_locked():
if action_name in self.database:
self.database[action_name].add(action_duration)
else:
new_action = Action(action_name, action_duration)
self.database[action_name] = new_action
def get_stats(self):
"""
Creates a string formatted json object of all actions in self.database, along with the average time.
:return: string formatted json object
"""
stats = []
with self.lock.r_locked():
for action_name in self.database:
action = self.database[action_name]
new_item = {
"action": action_name,
"avg": action.get_average()
}
stats.append(new_item)
return json.dumps(stats)