Tell us what’s happening:
I am having trouble understanding what’s wrong here.
The answer seems to match the example.
Your code so far
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
return False
def get_balance(self):
return sum(entry['amount'] for entry in self.ledger)
def transfer(self, amount, other_category):
if self.check_funds(amount):
self.withdraw(amount, f"Transfer to {other_category.name}")
other_category.deposit(amount, f"Transfer from {self.name}")
return True
return False
def check_funds(self, amount):
return self.get_balance() >= amount
def __str__(self):
title = f"{self.name:*^30}"
ledger_entries = "\n".join(
f"{entry['description'][:23]:23}{entry['amount']:7.2f}"
for entry in self.ledger
)
total = f"Total: {self.get_balance():.2f}"
return f"{title}\n{ledger_entries}\n{total}"
def create_spend_chart(categories):
# Calculate the total amount spent and the amount spent per category
total_spent = 0
category_spent = {}
for category in categories:
spent = sum(entry['amount'] for entry in category.ledger if entry['amount'] < 0)
category_spent[category.name] = -spent
total_spent += -spent
# Calculate the percentage spent per category
category_percentages = {name: (spent / total_spent) * 100 for name, spent in category_spent.items()}
# Create the chart
chart = ["Percentage spent by category"]
for i in range(100, -1, -10):
line = f"{i:>3}| "
for category in categories:
percentage = category_percentages[category.name]
line += "o " if percentage >= i else " "
chart.append(line.rstrip())
chart.append(" " + "-" * (len(categories) * 3 + 1))
max_name_length = max(len(cat.name) for cat in categories)
for i in range(max_name_length):
line = " "
for category in categories:
name = category.name
line += name[i] + " " if i < len(name) else " "
chart.append(line.rstrip())
return "\n".join(chart)
food = Category('Food')
food.deposit(1000, 'initial deposit')
food.withdraw(80.15, 'groceries')
food.withdraw(15.89, 'restaurant and more food for dessert')
clothing = Category('Clothing')
clothing.deposit(500, 'initial deposit')
clothing.withdraw(50.55, 'clothes')
entertainment = Category('Auto')
entertainment.deposit(500, 'initial deposit')
entertainment.withdraw(25, 'movies')
food.transfer(50, clothing)
#print(food)
#print(clothing)
#print(entertainment)
print(create_spend_chart([food, clothing, entertainment]))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
Challenge Information:
Build a Budget App Project - Build a Budget App Project