Build a Budget App Project - Build a Budget App Project

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

Check the browser console area (F12) for a more detailed output. Look for the Assertion Error.

I Have had a look and it says my spacing is not correct and I’m loosing my mind trying to figure out where, as I really can’t see it

Take this as example:
image
The first line is yours, the second is the expected.
The +++++ signs indicate that you should have five spaces right at that position.

In other words, each line should always have the same width, no matter the number of non-space characters.

1 Like

Press F12 and check the browser console area. Look for the Assertion Error. It will give you more clear idea of spacing.

You can also highlight the chart in the instructions to understand the spacing a bit better.

Screenshot 2024-03-10 211440

1 Like
  • First you need to think about how to separate category name, hint > you can use dictionary comprehension and have that stored in a variable
  • Run a for loop to extract items from the ledger
  • Total the items with respect to percentage
  • Create chart, hint > use range with a step parameter
  • Have max length variable for spacing
  • Using .rstrip in the end
  • Happy Coding :smiley:
1 Like

Cheers this was very useful!

1 Like

This was great too! Thank-you

1 Like

Also thanks for the hint, managed to get it just now, more or less everything just needed shifting

I’m not sure what this advice is about, you just summarized what they’ve already done, including variable names?

Please stop spamming the forum.