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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
# excercise example found on CodeSignal
def solution(queries):
ret_list = [] # output
work_dict = {} # ledger-like, use accountid as hash for key, and for val use (id,balance) list
act_dict = {}
for l in queries:
operation, timestamp, account_id = l[0], l[1], l[2]
if operation == 'CREATE_ACCOUNT':
if work_dict.get(account_id) is not None:
ret_list.append("false") # account already present
else:
work_dict[account_id] = [account_id, 0] # add id,balance list to dict
ret_list.append("true")
act_dict[account_id] = 0
elif operation == "DEPOSIT":
if work_dict.get(account_id) is None:
ret_list.append("")
else:
current_balance = work_dict[account_id][1]
work_dict[account_id][1] = current_balance + int(l[3])
ret_list.append(str(work_dict[account_id][1]))
act_dict[account_id] += int(l[3])
elif operation == "PAY":
if work_dict.get(account_id) is None:
ret_list.append("")
else:
current_balance = work_dict[account_id][1]
if current_balance >= int(l[3]):
work_dict[account_id][1] = current_balance - int(l[3])
ret_list.append(str(work_dict[account_id][1]))
act_dict[account_id] += int(l[3])
else:
ret_list.append("")
elif operation == "TOP_ACTIVITY":
n = int(l[2]) # top n accounts
top_string = ""
for w in sorted(act_dict, key=act_dict.get, reverse=True)[:n]:
top_string += f"{str(w)}({act_dict[w]}), "
ret_list.append(top_string[:-2])
return ret_list
q = [["CREATE_ACCOUNT","1","account1"],
["CREATE_ACCOUNT","2","account2"],
["CREATE_ACCOUNT","3","account3"],
["DEPOSIT","4","account1","1000"],
["DEPOSIT","5","account2","1000"],
["DEPOSIT","6","account3","1000"],
["PAY","7","account2","100"],
["PAY","8","account2","100"],
["PAY","9","account3","100"],
["TOP_ACTIVITY","10","3"]]
print(solution(q))
'''Expected Output:
["true",
"true",
"true",
"1000",
"1000",
"1000",
"900",
"800",
"900",
"account2(1200), account3(1100), account1(1000)"]
'''
'''Warmup excercise:
given following list of lists:
queries = [
["ADD", "1"],
["ADD", "2"],
["ADD", "5"],
["ADD", "2"],
["EXISTS", "2"],
["EXISTS", "5"],
["EXISTS", "1"],
["EXISTS", "4"],
["EXISTS", "3"],
["EXISTS", "0"]
]
that will be passed into following function that will be called once:
def solution(queries):
what code can produces following output:
["", "", "", "", "true", "true", "true", "false", "false", "false"]
My solution:
def solution(queries):
mylist = []
ret = []
for l in queries:
if l[0] == 'ADD':
mylist.append(l[1])
ret.append("")
elif l[0] == 'EXISTS':
if l[1] in mylist:
ret.append("true")
else:
ret.append("false")
return ret%
'''
|