Build a Budget App Project - Build a Budget App Project

Tell us what’s happening:

I’ve been stuck on this for hours, could someone help me please?
17. create_spend_chart should print a different chart representation, Check that all spacing is exact.

Your code so far

class Category:
    def __init__(self, name):
        self.name = name
        self.ledger = []  # Ledger to store all transactions
        self.balance = 0

    def __str__(self):
        title = f"{self.name:*^30}\n"
        transactions_str = ""
        for transaction in self.ledger:
            transactions_str += f"{transaction['description'][:23]:23}" + \
                                f"{transaction['amount']:>7.2f}\n"
        total = f"Total: {self.balance:.2f}"
        return title + transactions_str + total

    def deposit(self, amount, description=""):
        self.ledger.append({"amount": amount, "description": description})
        self.balance += amount

    def withdraw(self, amount, description=""):
        if self.check_funds(amount):
            self.ledger.append({"amount": -amount, "description": description})
            self.balance -= amount
            return True
        return False

    def get_balance(self):
        return self.balance

    def transfer(self, amount, another_category):
        if self.check_funds(amount):
            self.withdraw(amount, f"Transfer to {another_category.name}")
            another_category.deposit(amount, f"Transfer from {self.name}")
            return True
        return False

    def check_funds(self, amount):
        return self.balance >= amount


def create_spend_chart(categories):
    total_spent = 0
    spent_by_category = []

    # Calculate total spent and amount spent per category
    for category in categories:
        total = 0
        for transaction in category.ledger:
            if transaction["amount"] < 0:
                total += abs(transaction["amount"])
        spent_by_category.append({"category": category.name, "spent": total})
        total_spent += total

    # Calculate percentage spent for each category (rounded down to nearest 10)
    percentages = []
    for spent in spent_by_category:
        percentage = int((spent["spent"] / total_spent) * 100)
        percentages.append({"category": spent["category"], "percentage": percentage // 10 * 10})

    # Create chart header
    chart = "Percentage spent by category\n"
    
    # Create chart body with percentages
    for i in range(100, -1, -10):
        chart += f"{i:>3}| "
        for percentage in percentages:
            if percentage["percentage"] >= i:
                chart += "o  "
            else:
                chart += "   "
        chart += "\n"

    # Add the bottom border line
    chart += "    -" + "---" * len(categories) + "\n"
    
    # Determine the maximum length of category names for vertical labels
    max_length = max(len(category.name) for category in categories)
    
    # Create the vertical label for each category, letter by letter
    for i in range(max_length):
        chart += "     "  # 5 spaces of padding at the start
        for category in categories:
            if i < len(category.name):
                chart += category.name[i] + "  "
            else:
                chart += "   "
        chart += "\n"

    return chart.rstrip()  # Remove trailing newline or whitespace

# Test data
food = Category("Food")
clothing = Category("Clothing")
entertainment = Category("Entertainment")

# Adjusted transactions to ensure 60% spent
food.deposit(1000, "initial deposit")
food.withdraw(300, "groceries")  # Spent: 300
clothing.deposit(500, "initial deposit")
clothing.withdraw(100, "clothes")  # Spent: 100
entertainment.deposit(500, "initial deposit")
entertainment.withdraw(50, "movies")  # Spent: 50

# Create and print spend chart
categories = [food, clothing, entertainment]
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/129.0.0.0 Safari/537.36

Challenge Information:

Build a Budget App Project - Build a Budget App Project

If you open browser’s console there will be displayed details regarding the failing test.

1 Like

thanks, i just found the error