Build a Budget App - Build a Budget App

Tell us what’s happening:

Hey, so I am struggling on test cases #19, #20, #24 for creating the spend chart, it is saying there are issues with the formatting but I can’t seem to figure out what the issue is.

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 not self.check_funds(amount):
            return False
        else:
            self.ledger.append({'amount': -(amount), 'description': description})
            return True
    
    def get_balance(self):
        balance = 0
        for actions in self.ledger:
            balance += actions.get('amount')
        return balance
    
    def transfer(self, amount, category):
        if not isinstance(category, Category) or not self.check_funds(amount):
            print("Transfer failed")
            return False
        self.ledger.append({'amount': -(amount), 'description': f"Transfer to {category.name}"})
        category.ledger.append({'amount': amount, 'description': f"Transfer from {self.name}"})
        return True

    def check_funds(self, amount):
        if self.get_balance() >= amount:
            return True
        else:
            return False
    
    def __str__(self):
        table = ''
        carry = (30 - len(self.name)) % 2
        split = math.floor((30 - len(self.name)) / 2)
        star = '*'
        space = ' '
        table += f"{star * split}{self.name}{star * (split + carry)}\n"
        
        for action in self.ledger:
            detail = action['description']
            spaceCount = 30 - len(detail[:23]) - len(f"{action.get('amount'):.2f}")
            table += f"{detail[:23]}{space * spaceCount}{action.get('amount'):.2f}\n"

        table += f"Total: {self.get_balance():.2f}"
        return table

def create_spend_chart(categories):
    barchart = ''
    yaxis = 100
    totalSpent = 0
    percentage = []
    
    for category in categories:
        spent = 0
        for action in category.ledger:
            if action['amount'] < 0:
                totalSpent += -(action['amount'])
                spent += -(action['amount'])

        percentage.append(spent)

    for index, spent in enumerate(percentage):
        percent = (spent / totalSpent) * 100
        percent = math.floor(percent / 10)*10
        percentage[index] = percent
    
    while yaxis >= 0:
        if yaxis == 100:
            barchart += f"{yaxis}| "
        elif yaxis == 0:
            barchart += f"  {yaxis}| "
        else:
            barchart += f" {yaxis}| "
        for percent in percentage:
            barchart += "o  " if percent >= yaxis else " "
        barchart += '\n'
        yaxis -= 10
    
    barchart += '    ' + '---' * (len(percentage)) + '-\n'
    maxLen = 0
    for item in categories:
       maxLen = max(maxLen, len(item.name))
    
    for idx in range(maxLen):
        barchart += '     '
        for item in categories:
            if idx < len(item.name):
                barchart += item.name[idx] + '  '
            else:
                barchart += '   '
        barchart += '\n'
    
    return "Percentage spent by category\n" + barchart.rstrip('\n') 


food = Category('Food')
food.deposit(1000, 'initial deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.89, 'restaurant and more food for dessert')
clothing = Category('Clothing')
food.transfer(50, clothing)
clothing.withdraw(25, 'pants')
print(create_spend_chart([food, clothing]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:152.0) Gecko/20100101 Firefox/152.0

Challenge Information:

Build a Budget App - Build a Budget App

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-budget-app/5e44413e903586ffb414c94e.md at main · freeCodeCamp/freeCodeCamp · GitHub

Hi @amanimashaun,

I’m seeing these assertion errors in the browser’s console after running the tests:

False is not true : Expected different rounding of bars.

From the instructions:

The percentage should be the percentage of the amount spent for each category to the total spent for all categories (rounded down to the nearest 10).

'Expected different chart representation. Check that all spacing is exact.'
'Perc[29 chars]|    \n 90|    \n 80|    \n 70|  o   \n 60|  o[303 chars] t  ' != 
'Perc[29 chars]|          \n 90|          \n 80|          \n [345 chars] t  '
7 != 11: Expected different length of the chart line. Check that all spacing is exact.

Happy coding

For rounding down to the nearest 10; doesn’t this code accomplish that?

for index, spent in enumerate(percentage):
        percent = (spent / totalSpent) * 100
        percent = math.floor(percent / 10)*10
        percentage[index] = percent

Thanks I figured it out! The problem was that I missed adding some extra spaces when percent < yaxis :+1: