Created
January 16, 2024 21:19
-
-
Save berdfandrade/6fd1282d29e7e314b5054348bd7a7daa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Category: | |
def __init__(self, name): | |
self.name = name | |
self.ledger = [] | |
def deposit(self, amount, description=""): | |
self.ledger.append({"amount": amount, "description": description}) | |
def withdraw(self, amount, description=""): | |
if self.check_funds(amount): | |
self.ledger.append({"amount": -amount, "description": description}) | |
return True | |
else: | |
return False | |
def get_balance(self): | |
balance = 0 | |
for transaction in self.ledger: | |
balance += transaction["amount"] | |
return balance | |
def transfer(self, amount, category): | |
if self.check_funds(amount): | |
self.withdraw(amount, f"Transfer to {category.name}") | |
category.deposit(amount, f"Transfer from {self.name}") | |
return True | |
else: | |
return False | |
def check_funds(self, amount): | |
return amount <= self.get_balance() | |
def __str__(self): | |
title = f"{self.name:*^30}\n" | |
items = "" | |
total = 0 | |
for transaction in self.ledger: | |
description = transaction["description"][:23].ljust(23) | |
amount = "{:.2f}".format(transaction["amount"]).rjust(7) | |
items += f"{description}{amount}\n" | |
total += transaction["amount"] | |
output = title + items + "Total: {:.2f}".format(total) | |
return output | |
def create_spend_chart(categories): | |
category_names = [] | |
spent_percentages = [] | |
spent_amount = 0 | |
for category in categories: | |
withdrawals = sum( | |
transaction["amount"] | |
for transaction in category.ledger | |
if transaction["amount"] < 0 | |
) | |
spent_amount += withdrawals | |
category_names.append(category.name) | |
spent_percentages.append(withdrawals) | |
# Calculate the percentage spent for each category | |
spent_percentages = [ | |
int((percentage / spent_amount) * 10) * 10 | |
for percentage in spent_percentages | |
] | |
chart = "Percentage spent by category\n" | |
for i in range(100, -10, -10): | |
chart += str(i).rjust(3) + "| " | |
for percentage in spent_percentages: | |
if percentage >= i: | |
chart += "o " | |
else: | |
chart += " " | |
chart += "\n" | |
chart += " ----------\n" | |
# Find the longest name length | |
max_name_length = max(len(name) for name in category_names) | |
for i in range(max_name_length): | |
chart += " " | |
for name in category_names: | |
if i < len(name): | |
chart += name[i] + " " | |
else: | |
chart += " " | |
if i != max_name_length - 1: | |
chart += "\n" | |
return chart |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment