-
Notifications
You must be signed in to change notification settings - Fork 0
/
isaac_final.py
76 lines (59 loc) · 2 KB
/
isaac_final.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
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
from datetime import datetime
from uuid import uuid4
class Expense:
def __init__(self, title, amount):
self.id = uuid4()
self.title = title
self.amount = amount
self.created_at = datetime.now()
self.updated_at = self.created_at
def update(self, new_title=None, new_amount=None):
if new_title:
self.title = new_title
if new_amount:
self.amount = new_amount
self.updated_at = datetime.now()
def to_dict(self):
return {
"id": self.id,
"title": self.title,
"amount": self.amount,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat()
}
class ExpenseDB:
def __init__(self):
self.expenses = []
def add_expense(self, expense: Expense):
self.expenses.append(expense)
def remove_expense(self, expense_id):
self.expenses = [expense for expense in self.expenses if expense.id != expense_id]
def get_expense_by_id(self, expense_id):
for expense in self.expenses:
if expense.id == expense_id:
return expense
return None
def get_expenses_by_title(self, title):
return [expense for expense in self.expenses if expense.title == title]
def to_dict(self):
return {"expenses": [expense.to_dict() for expense in self.expenses]}
# Example usage
expense1 = Expense("Groceries", 100)
expense2 = Expense("Utilities", 50)
db = ExpenseDB()
db.add_expense(expense1)
db.add_expense(expense2)
# Update an expense
expense1.update(new_amount=120)
# Retrieve an expense by ID and print it
expense_by_id = db.get_expense_by_id(1)
if expense_by_id:
print(expense_by_id.to_dict())
# Retrieve expenses by title and print them
expenses_by_title = db.get_expenses_by_title("Utilities")
for expense in expenses_by_title:
print(expense.to_dict())
# Remove an expense
db.remove_expense(2)
# Convert database to dictionary and print it
print(db.to_dict())