Tell us what’s happening:
I can’t figure out “create_spend_chart should print a different chart representation. Check that all spacing is exact. Open your browser console with F12 for more details.”
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(item["amount"] for item in self.ledger)
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
return False
def check_funds(self, amount):
return amount <= self.get_balance()
def __str__(self):
title = f"{self.name:*^30}\n"
items = ""
for entry in self.ledger:
description = entry["description"][:23]
amount = f"{entry['amount']:.2f}"
items += f"{description:<23}{amount:>7}\n"
total = f"Total: {self.get_balance():.2f}"
return title + items + total
def create_spend_chart(categories):
total_spent = 0
category_spending = []
# Calculate total spending and spending per category
for category in categories:
spent = sum(-item["amount"] for item in category.ledger if item["amount"] < 0)
category_spending.append((category.name, spent))
total_spent += spent
# Calculate percentages without rounding, keeping them exact
percentages = [(name, (spent / total_spent) * 100) for name, spent in category_spending]
# Chart title
chart = "Percentage spent by category\n"
# Add percentage bars (ensure no extra \n or spaces after the bar lines)
for i in range(100, -1, -10):
chart += f"{i:>3}|"
for _, percentage in percentages:
chart += " o " if percentage >= i else " "
chart += "\n"
# Add horizontal line
line_length = 3 * len(categories) + 1
chart += " " + "-" * line_length + "\n"
# Add category names vertically
max_name_length = max(len(name) for name, _ in percentages)
names = [name.ljust(max_name_length) for name, _ in percentages]
for i in range(max_name_length):
chart += " "
for name in names:
chart += f" {name[i]} "
if i < max_name_length - 1: # Ensure no trailing newlines after the last row
chart += "\n"
return chart.rstrip() # Remove any trailing space or newline
food = Category("Food")
food.deposit(1000, "deposit")
food.withdraw(10.15, "groceries")
food.withdraw(15.89, "restaurant and more food for dessert")
clothing = Category("Clothing")
food.transfer(50, clothing)
print(food)
print(create_spend_chart([food, clothing]))
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36
Challenge Information:
Build a Budget App Project - Build a Budget App Project