Tell us what’s happening:
I’m having a problem creating the function create_spend_chart.
the console says “create_spend_chart should print a different chart representation. Check that all spacing is exact.”
if someone could help that would be great
Your code so far
class Category:
def __init__(self, category):
self.category = category
self.ledger = []
def deposit(self, amount, description=""):
if amount > 0:
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, other_category):
if self.check_funds(amount):
self.withdraw(amount, f"Transfer to {other_category.category}")
other_category.deposit(amount, f"Transfer from {self.category}")
return True
return False
def check_funds(self, amount):
return amount <= self.get_balance()
def __str__(self):
# Title line centered
title = f"{self.category:*^30}"
# Ledger entries formatted
items = ""
for entry in self.ledger:
description = entry['description'][:23]
amount = f"{entry['amount']:>7.2f}"
items += f"{description:<23}{amount}\n"
# Total line
total = f"Total: {self.get_balance():.2f}"
return f"{title}\n{items}{total}"
def create_spend_chart(categories):
# Calculate total spending per category and round down to the nearest 10
category_spending = {}
for category in categories:
total_spent = sum(-item['amount'] for item in category.ledger if item['amount'] < 0)
rounded_spent = (total_spent // 10) * 10
category_spending[category.category] = rounded_spent
# Find the maximum rounded spending to determine the scale of the chart
max_spending = max(category_spending.values(), default=0)
# Create the chart header
chart = "Percentage spent by category\n"
# Create the chart lines
for i in range(100, -1, -10):
line = f"{i:>3}| "
for category in categories:
if category_spending[category.category] / max_spending * 100 >= i:
line += "o "
else:
line += " "
chart += line.rstrip() + " \n"
# Add the chart footer with category names
chart += " -" + "---" * len(categories) + "\n"
max_length = max(len(cat.category) for cat in categories)
for i in range(max_length):
line = " "
for category in categories:
if i < len(category.category):
line += category.category[i] + " "
else:
line += " "
chart += line.rstrip() + " \n"
return chart.rstrip()
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15
Challenge Information:
Build a Budget App Project - Build a Budget App Project