Build a Budget App Project - Build a Budget App Project

Tell us what’s happening:

I have tried multiple times, but I cannot pass the cases listed below:
23. create_spend_chart chart should have each category name written vertically below the bar. Each line should have the same length, each category should be separated by two spaces, with additional two spaces after the final category.
24. create_spend_chart should print a different chart representation.

Your code so far

import math

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.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):
        result = f"{self.name:*^30}\n"
        for item in self.ledger:
            amount = item["amount"]
            description = item["description"]
            result += f"{description[:23]:<23}{amount:>7.2f}\n"
        result += f"Total: {self.get_balance():.2f}"
        return result


def create_spend_chart(categories):
    total_spent = 0
    category_spent = {}

    # Calculate total spending per category and overall total
    for category in categories:
        spent = sum(-item["amount"] for item in category.ledger if item["amount"] < 0)
        total_spent += spent
        category_spent[category.name] = spent

    if total_spent == 0:
        return "Percentage spent by category\n"

    # Calculate percentages, rounding down to the nearest multiple of 10
    percentage_spent = {
        name: math.floor((spent / total_spent) * 10) * 10
        for name, spent in category_spent.items()
    }

    # Build the chart
    chart = "Percentage spent by category\n"

    for i in range(100, -1, -10):
        line = f"{i:>3}| "
        for name in percentage_spent:
            if percentage_spent[name] >= i:
                line += "o  "
            else:
                line += "   "
        chart += line + "\n"

    # Add the separator line
    chart += "    " + "-" * (3 * len(categories) + 1) + "\n"

    # Add category names vertically
    max_length = max(len(name) for name in category_spent.keys())

    for i in range(max_length):
        line = "     "  # Start with spacing for alignment
        for name in category_spent.keys():
            if i < len(name):
                line += name[i] + "  "
            else:
                line += "   "  # Add three spaces if no character exists
        chart += line.rstrip() + "\n"  # Remove trailing spaces and add a newline

    return chart.rstrip()  # Remove trailing newlines at the end of the chart


# Example usage:
food = Category("Food")
clothing = Category("Clothing")
auto = Category("Auto")

# Transactions for Food
food.deposit(1000, "initial deposit")
food.withdraw(60, "groceries")  # Spend 60 (60% of total)

# Transactions for Clothing
clothing.deposit(100, "initial deposit")  # Deposit enough to cover spending
clothing.withdraw(20, "spending")         # Spend 20 (20% of total)

# Transactions for Auto
auto.deposit(50, "initial deposit")       # Deposit enough to cover spending
auto.withdraw(10, "spending")             # Spend 10 (10% of total)

# Call the function to create the spend chart
categories = [food, clothing, auto]
print(create_spend_chart(categories))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36

Challenge Information:

Build a Budget App Project - Build a Budget App Project

Please check the error messages in the dev tools console (F12)

The assertion error and diff gives you a lot of information to track down a problem. For example:

E       AssertionError: Expected different output when calling "arithmetic_arranger()" with ["3801 - 2", "123 + 49"]
E       assert '  3801      123    \n   - 2     + 49    \n------    -----    \n' == '  3801      123\n-    2    +  49\n------    -----'

The first line is long, and it helps to view it as 2 lines in fixed width characters, so you can compare it character by character:

'  3801      123    \n   - 2     + 49    \n------    -----    \n'
'  3801      123\n-    2    +  49\n------    -----'

Again, your output is first and the expected output is second. Here it’s easy to see extra spaces or \n characters.

I hope this helps interpret your error!