Scientific Computing with Python Projects - Budget App

Hello, I have a problem with this code, I am in the last test, and I don’t know what I have wrong since the graph is identical to the one they give as an example.

Your code so far

class Category:
    def __init__(self, category_name):
        self.category_name = category_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, other_category):
        if self.check_funds(amount):
            self.withdraw(amount, f"Transfer to {other_category.category_name}")
            other_category.deposit(amount, f"Transfer from {self.category_name}")
            return True
        return False

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

    def __str__(self):
        title = f"{self.category_name:*^30}\n"
        items = ""
        total = 0

        for item in self.ledger:
            description = item["description"][:23]
            amount = format(item["amount"], ".2f")
            items += f"{description:<23}{amount:>7}\n"
            total += item["amount"]

        output = title + items + f"Total: {total:.2f}"
        return output

def create_spend_chart(categories):
    # Calculate the total withdrawals for all categories
    total_withdrawals = sum(category.get_balance() for category in categories)
    
    # Calculate the percentage spent for each category
    percentages = [(category.get_balance() / total_withdrawals) * 100 for category in categories]
    
    # Create the chart
    chart = "Percentage spent by category\n"
    for i in range(100, -1, -10):
        chart += f"{i:>3}| "
        for percent in percentages:
            if percent >= i:
                chart += "o  "
            else:
                chart += "   "
        chart += "\n"
    
    # Add the horizontal line
    chart += "    -" + "---" * len(categories) + "\n"
    
    # Find the length of the longest category name
    max_name_length = max(len(category.category_name) for category in categories)
    
    # Add category names vertically
    for i in range(max_name_length):
        chart += "     "
        for category in categories:
            if i < len(category.category_name):
                chart += category.category_name[i] + "  "
            else:
                chart += "   "
        chart += "\n"
    
    return chart



categoria_comida = Category("Food")
categoria_comida.deposit(100, "Comestibles")
categoria_comida.withdraw(0, "Gastos de restaurante")

categoria_ropa = Category("Clothing")
categoria_ropa.deposit(35, "Zapatos nuevos")
categoria_ropa.withdraw(0, "Camiseta")

categoria_entretenimiento = Category("Auto")
categoria_entretenimiento.deposit(30, "Entradas para conciertos")
categoria_entretenimiento.withdraw(0, "Noche de cine")

lista_categorias = [categoria_comida, categoria_ropa,  categoria_entretenimiento]
resultado_grafico = create_spend_chart(lista_categorias)
print(resultado_grafico)

Your browser information:

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

Challenge Information:

Scientific Computing with Python Projects - Budget App

Your test chart does look good.

Here is the data the test uses:

food = Category("Food")
entertainment = Category("Entertainment")
business = Category("Business")    
food.deposit(900, "deposit")
entertainment.deposit(900, "deposit")
business.deposit(900, "deposit")

food.withdraw(105.55)
entertainment.withdraw(33.40)
business.withdraw(10.99)

print(repr(create_spend_chart([business, food, entertainment]))

And here is the expected output:

'Percentage spent by category\n100|          \n 90|          \n 80|          \n 70|    o     \n 60|    o     \n 50|    o     \n 40|    o     \n 30|    o     \n 20|    o  o  \n 10|    o  o  \n  0| o  o  o  \n    ----------\n     B  F  E  \n     u  o  n  \n     s  o  t  \n     i  d  e  \n     n     r  \n     e     t  \n     s     a  \n     s     i  \n           n  \n           m  \n           e  \n           n  \n           t  '

Here is the output I get with your code:

'Percentage spent by category\n100|          \n 90|          \n 80|          \n 70|          \n 60|          \n 50|          \n 40|          \n 30| o  o  o  \n 20| o  o  o  \n 10| o  o  o  \n  0| o  o  o  \n    ----------\n     B  E  F  \n     u  n  o  \n     s  t  o  \n     i  e  d  \n     n  r     \n     e  t     \n     s  a     \n     s  i     \n        n     \n        m     \n        e     \n        n     \n        t     \n'

One problem is the trailing \n at the end.

The charts are different as well
Your output:

Percentage spent by category
100|          
 90|          
 80|          
 70|          
 60|          
 50|          
 40|          
 30| o  o  o  
 20| o  o  o  
 10| o  o  o  
  0| o  o  o  
    ----------
     B  E  F  
     u  n  o  
     s  t  o  
     i  e  d  
     n  r     
     e  t     
     s  a     
     s  i     
        n     
        m     
        e     
        n     
        t     

and the expected:

Percentage spent by category
100|          
 90|          
 80|          
 70|    o     
 60|    o     
 50|    o     
 40|    o     
 30|    o     
 20|    o  o  
 10|    o  o  
  0| o  o  o  
    ----------
     B  F  E  
     u  o  n  
     s  o  t  
     i  d  e  
     n     r  
     e     t  
     s     a  
     s     i  
           n  
           m  
           e  
           n  
           t  
1 Like

This looks like it needs to be fixed:

    # Calculate the total withdrawals for all categories
    total_withdrawals = sum(category.get_balance() for category in categories)

I solved the problem with the bar, but it still gives me the error
image

1 Like

:face_with_monocle: Damn. I suspect you might have a stray \n at the end? Otherwise looks good.

Can you post your updated code, please?

this was the change, when starting create_spend_chart

Calculate the total withdrawals for all categories

total_withdrawals = sum(category.ledger[1]["amount"]  for category in categories)*-1

# Calculate the percentage spent for each category
percentages = [((category.ledger[1]["amount"]*-1) / total_withdrawals) * 100 for category in categories]

Then you will still have this trailing '\n' and some extra spaces at the end of your chart. There needs to be 2 spaces and no \n

2 Likes

oh god, thank, only for that, How awful!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.