Tell us what’s happening:
I’m Very stuck on the last question as I don’t really understand what it’s asking for
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 amount <= self.get_balance()
def __str__(self):
# Title line
title_line = f"{self.name:*^30}"
# Ledger items
ledger_lines = [f"{entry['description'][:23]:<23}{entry['amount']:>7.2f}" for entry in self.ledger]
# Total line
total_line = f"Total: {self.get_balance():.2f}"
return "\n".join([title_line] + ledger_lines + [total_line])
def create_spend_chart(categories):
# Calculate total spend for each category
spendings = {category.name: sum(-entry['amount'] for entry in category.ledger if entry['amount'] < 0) for category in categories}
total_spent = sum(spendings.values())
# Calculate percentage spend for each category
if total_spent == 0:
percentages = {name: 0 for name in spendings}
else:
percentages = {name: (spend / total_spent) * 100 for name, spend in spendings.items()}
# Create the chart
chart = "Percentage spent by category\n"
# Generate the chart from 100% down to 0%
for i in range(100, -10, -10):
chart += f"{i:>3}| "
for category in categories:
if percentages[category.name] >= i:
chart += "o "
else:
chart += " "
chart = chart.rstrip() + "\n" # Remove trailing spaces
# Add the horizontal line at the bottom
chart += " " + "-" * (3 * len(categories) + 1) + "\n"
# Create vertical labels
max_length = max(len(category.name) for category in categories)
for i in range(max_length):
chart += " "
for category in categories:
if i < len(category.name):
chart += f"{category.name[i]} "
else:
chart += " "
chart += "\n"
return chart
food = Category("Food")
clothing = Category("Clothing")
entertainment = Category("Entertainment")
food.deposit(1000, "Initial deposit")
food.withdraw(100, "Groceries")
food.withdraw(50, "Restaurant")
clothing.deposit(500, "Initial deposit")
clothing.withdraw(60, "Clothes")
entertainment.deposit(300, "Initial deposit")
entertainment.withdraw(200, "Movies")
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