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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
| import json
import os
def check_user():
tries = 0
while tries < 3:
file_json = "users.json"
with open(file_json, "r") as f:
users_data = json.load(f)
username = input("Введіть ім'я користувача: ")
password = input('Введіть пароль: ')
if any(i.get('username') == username for i in users_data):
if any(i.get('password') == password for i in users_data):
print("Ви ввійшли до банківської системи!\n")
if username and password == 'admin':
atm_collection(username)
return username
else:
print('Ви ввели невірний пароль !')
tries += 1
else:
print("Будь ласка, введіть коректне ім'я!")
tries += 1
print('Вибачне, але Ви тричі ввели невірні данні.\n Ваша картка буде заблокована!')
return False
def atm_collection(user):
while True:
selection = int(input('''Введіть дію:
1. Переглянути залишок коштів у банкоматі
2. Поповнити банкомат
3. Добавити користувача
4. Вихід
Ваш вибір: '''))
if selection == 1:
print('Перегляд балансу банкомату.')
operation = "check balance ATM"
print(f'Всього в банкоматі {check_balance_ATM(operation)} грн.\n')
elif selection == 2:
print('Поповнення банкомату.')
load_atm(user)
elif selection == 3:
addUser()
elif selection == 4:
print('Вихід!')
print('Дякуємо за Ваш вибір!')
break
else:
print('Неправильний вибір! Повторіть спробу!')
else:
print('Програма "Банкомат" завершила свою роботу!')
def get_money(money):
lst_banknotes = [1000, 500, 200, 100, 50, 20, 10 ]
INF = 10000000
F = [INF] * (money + 1)
F[0] = 0
for k in range(1, money + 1):
for i in range(len(lst_banknotes)):
if k - lst_banknotes[i] >= 0 and F[k - lst_banknotes[i]] < F[k]:
F[k] = F[k - lst_banknotes[i]]
F[k] += 1
result_banknotes = []
k = money
while k != 0:
for i in range(len(lst_banknotes)):
if k - lst_banknotes[i] >= 0 and F[k] == F[k - lst_banknotes[i]] + 1:
result_banknotes.append(lst_banknotes[i])
k -= lst_banknotes[i]
return result_banknotes
def check_enough_banknotes_atm(money):
lst_banknotes = get_money(money)
dict_number_banknotes = {str(i): lst_banknotes.count(i) for i in lst_banknotes}
user = 'admin'
user_file = user + "_balance.json"
with open(user_file, "r") as f:
dict_admin_balance = json.load(f)
result_dict = {key: dict_admin_balance[key] - dict_number_banknotes[key] for key in dict_admin_balance if
key in dict_number_banknotes}
return all(value >= 0 for value in result_dict.values())
def check_balance_ATM(operation):
user = 'admin'
user_file = user + "_balance.json"
with open(user_file, "r") as f:
admin_balance = json.load(f)
all_money = (sum(int(bancknote) * value for bancknote, value in admin_balance.items()))
if operation == "check balance ATM":
print(f'Всього у банкоматі: {all_money} грн.', '\n')
print('У банкоматі знаходиться: ')
for bancknote, value in admin_balance.items():
print(f"Банкнот {bancknote} грн. - {value} шт.")
add_transaction(user, operation, all_money)
return all_money
def check_banknote(user, banknote):
user_file = user + "_balance.json"
with open(user_file, "r") as f:
admin_balance = json.load(f)
banknote = str(banknote)
return admin_balance[banknote]
def add_cash_to_atm(user, banknote, number):
user_file = user + "_balance.json"
with open(user_file, "r") as f:
admin_balance = json.load(f)
banknote = str(banknote)
admin_balance[banknote] += number
with open(user_file, "w") as f:
json.dump(admin_balance, f)
with open(user_file, "r") as f:
balance = json.load(f)
operation = "load ATM"
banknote = int(banknote)
money = banknote * number
add_transaction(user, operation, money)
print(f'В банкомат завантажено {number} банкнот по {banknote} грн. Всього завантажено {money} грн.\n')
def load_atm(user):
banknote = input('Введіть номінал поповнення 10, 20, 50, 100, 200, 500 чи 1000 грн.: ')
if banknote.isdigit():
banknote = int(banknote)
if banknote in [10, 20, 50, 100, 200, 500, 1000]:
number = input('Введіть кількість банкнот поповнення: ')
if number.isdigit():
number = int(number)
if 0 < number < 100:
banknotes_in_atm = check_banknote(user, banknote)
if number + banknotes_in_atm <= 100:
add_cash_to_atm(user, banknote, number)
else:
print(f'В банкоматі банкнота {banknote} грн. у кількості {banknotes_in_atm} шт. \n\
Можна цю банкноту покласти у кількості {100 - banknotes_in_atm} шт.')
else:
print('В банкомат можна завантажити від 1 до 100 банкнот. Ввведіть коректну кількість.')
else:
print('Будь ласка, введіть лише цифрове значення!\n')
else:
print('Банкомат не підтримує даний номінал!')
else:
print('Будь ласка, введіть лише цифрове значення!\n')
def add_transaction(user, operation, money):
transaction_file = user + "_transactions.json"
if os.path.isfile(transaction_file):
with open(transaction_file, "r", encoding="utf-8") as f:
info = json.load(f)
number_transaction = info[-1]["Transaction"] + 1
else:
number_transaction = 1
if operation == "deposite":
money = "+" + str(money)
elif operation == "withdraw":
money = "-" + str(money)
user_info = {"Transaction": number_transaction,
"Operation": operation,
"Balance": money}
if os.path.isfile(transaction_file):
with open(transaction_file, "r", encoding="utf-8") as f:
info = json.load(f)
info.append(user_info)
with open(transaction_file, "w", encoding="utf-8") as f:
json.dump(info, f, indent=4, ensure_ascii=False)
else:
with open(transaction_file, "w", encoding="utf-8") as f:
lst = []
lst.append(user_info)
json.dump(lst, f, indent=4, ensure_ascii=False)
return
def check_balance(user, operation):
user_file = user + "_balance.json"
with open(user_file, "r") as f:
balance = json.load(f)
money = balance["account"]
if operation == "deposite" or operation == "withdraw":
return money
else:
add_transaction(user, operation, money)
return money
def deposite(user, money):
user_file = user + "_balance.json"
with open(user_file, "r") as f:
balance = json.load(f)
balance["account"] += money
with open(user_file, "w") as f:
json.dump(balance, f)
with open(user_file, "r") as f:
balance = json.load(f)
operation = "deposite"
add_transaction(user, operation, money)
return balance["account"]
def withdraw(user, money):
operation = "withdraw"
user_file = user + "_balance.json"
with open(user_file, "r") as f:
balance = json.load(f)
balance["account"] -= money
with open(user_file, "w") as f:
json.dump(balance, f)
add_transaction(user, operation, money)
lst_banknotes = get_money(money)
dict_number_banknotes = {str(i): lst_banknotes.count(i) for i in lst_banknotes}
user = 'admin'
user_file = user + "_balance.json"
with open(user_file, "r") as f:
dict_admin_balance = json.load(f)
result_dict = {key: dict_admin_balance[key] - dict_number_banknotes[key] for key in dict_admin_balance if
key in dict_number_banknotes}
dict_admin_balance.update(result_dict)
dict_digit = {int(k): v for k, v in dict_admin_balance.items()}
dict_digit_sorted = dict(sorted(dict_digit.items()))
dict_admin_balance_str = {str(k): v for k, v in dict_digit_sorted.items()}
with open(user_file, "w") as f:
json.dump(dict_admin_balance_str, f)
add_transaction(user, operation, money)
return
def addUser():
users_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'users.json')
with open(users_data, 'r') as write_file:
users = json.load(write_file)
username = input('Введіть імя нового користувача: ')
password = input("Введіть новий пароль користувача: ")
user_info = {'username': username, 'password': password}
users.append(user_info)
with open(users_data, 'w') as write_file:
json.dump(users, write_file)
print(f'Ви добавили {username} користувача')
def start():
user = check_user()
if user and user != 'admin':
while True:
selection = int(input('''Введіть дію:
1. Продивитись баланс
2. Поповнити баланс
3. Зняти кошти
4. Вихід
Ваш вибір: '''))
if selection == 1:
print('Перегляд балансу.')
operation = "check balance"
print(f'На Вашому рахунку {check_balance(user, operation)} грн.\n')
elif selection == 2:
print('Поповнення балансу.')
money = input('Введіть суму поповнення: ')
if money.isdigit():
money = int(money)
if money in [1000, 500, 200, 100, 50, 20]:
print(f'На Вашому рахуноку {deposite(user, money)} грн., його поповнено на суму {money} грн.\n')
else:
print('Банкомат приймає лише номінали 10,20, 50, 100, 200, 500 або 1000 грн.!\n')
else:
print('Будь ласка, введіть лише цифрове значення!\n')
elif selection == 3:
print('Зняття коштів.')
operation = "withdraw"
money = input('Введіть необхідну суму: ')
if money.isdigit():
money = int(money)
if money != 0 and money % 10 == 0 and money not in [10, 30]:
if check_balance(user, operation) - money >= 0:
if check_balance_ATM(operation) - money >= 0:
if check_enough_banknotes_atm(money):
withdraw(user, money)
print(
f'На Вашому рахуноку {check_balance(user, operation)} грн., з нього знято {money} грн.')
print('Купюрами: ', get_money(money), 'грн.\n')
else:
print('У банкоматі немає банкнот для видачі зазначену суму!')
else:
print('На даний момент у банкоматі недостатньо коштів для видачі вказаної суми!\n')
else:
print('На Вашому рахунку недостатньо коштів!\n')
else:
print(
f'Введенної суми, {money} грн., банкомат не може видати наявними номіналами 20, 50, 100, 200, 500 і 1000 грн!')
else:
print('Будь ласка, введіть лише цифрове значення!\n')
elif selection == 4:
print('Вихід!')
print('Дякуємо за Ваш вибір!')
print('Програма "Банкомат" завершила свою роботу!')
break
else:
print('Неправильний вибір! Повторіть спробу!')
else:
print('Програма "Банкомат" завершила свою роботу!')
start() |