Build a Budget App Project - Build a Budget App Project

Tell us what’s happening:

El proyecto Proyecto de creación de una aplicación de presupuesto, el metodo create_spend_chart, pide crear un gráfico, con las mismas dimensiones pero diferente al del ejemplo, lo he hecho de forma vertical, horizontal y me sigue fallando el último punto con el siguiente error: " create_spend_chart Debe imprimir una representación gráfica diferente. Verifique que el espaciado sea exacto." ayuda, es el último punto que me falta para la cerificación.

Your code so far

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

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

    def __str__(self):
        title = self.nombre.center(30, '*')
        items = [f"{item['description'][:23].ljust(23)}{item['amount']:7.2f}" for item in self.ledger]
        total = f"Total: {self.get_balance():.2f}"
        return '\n'.join([title] + items + [total])


def create_spend_chart(categories):
    # Calcular el total gastado en cada categoría
    total_spent = {}
    for category in categories:
        spent = sum(-item['amount'] for item in category.ledger if item['amount'] < 0)
        total_spent[category.nombre] = spent

    total_expenses = sum(total_spent.values())

    # Calcular el porcentaje gastado en cada categoría
    if total_expenses == 0:
        percentages = {cat: 0 for cat in total_spent}
    else:
        percentages = {cat: (spent / total_expenses) * 100 for cat, spent in total_spent.items()}

    # Construir el gráfico
    chart = ["Percentage spent by category"]
    
    # Generar las líneas del gráfico
    for i in range(100, -1, -10):
        line = f"{i:3}| "
        for cat in categories:
            if percentages[cat.nombre] >= i:
                line += "o  "
            else:
                line += "   "
        chart.append(line.rstrip())

    chart.append("    " + "-" * (len(categories) * 3 + 1))
    
    # Añadir nombres de categorías en la parte inferior
    max_name_length = max(len(cat.nombre) for cat in categories)
    for i in range(max_name_length):
        line = "    "
        for cat in categories:
            name = cat.nombre
            if i < len(name):
                line += f"{name[i]}  "
            else:
                line += "   "
        chart.append(line.rstrip())

    return '\n'.join(chart)

# Crear categorías
food = Category('Food')
food.deposit(150, 'initial deposit')
food.withdraw(100.15, 'groceries')
food.withdraw(250.89, 'restaurant and more food for dessert')

clothing = Category('Clothing')
clothing.deposit(50, 'initial deposit')
clothing.withdraw(35.55, 'clothes')
clothing.withdraw(85.25, 'shoes')

auto = Category('Auto')
auto.deposit(500, 'initial deposit')
auto.withdraw(100, 'Tires')
auto.withdraw(150, 'paint')

# Transferir dinero
food.transfer(50, clothing)

# Imprimir las categorías
print(food)
print(clothing)

# Crear gráfico de gastos
print(create_spend_chart([food, clothing,auto]))

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

¿Has comprobado el mensaje de devtools? (Presiona F12)

si, el problema es que no logro darle solución al último punto de las validaciones, el código funciona e imprime un gráfico diferente pero no logró cumplirlo.

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

AssertionError: 'Year' != 'Years'
- Year
+ Years
?     +

Your output comes first, and the output that the test expects is second.

AssertionError: ‘Year’ != ‘Years’

Your output: Year does not equal what’s expected: Years

This is called a diff, and it shows you the differences between two files or blocks of code:

- Year
+ Years
?     +

- Dash indicates the incorrect output
+ Plus shows what it should be
? The Question mark line indicates the place of the character that’s different between the two lines. Here a + is placed under the missing s .

Here’s another 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------    -----'
E         -   3801      123
E         +   3801      123    
E         ?                ++++
E         - -    2    +  49
E         +    - 2     + 49    
E         - ------    -----
E         + ------    -----    
E         ?                +++++

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.

E         -   3801      123
E         +   3801      123    
E         ?                ++++

Here the ? line indicates 4 extra spaces at the end of a line using four + symbols. Spaces are a little difficult to see this way, so it’s useful to use both formats together.

I hope this helps interpret your error!

AssertionError: 
'Perc[25 chars]n100|\n 90|\n 80|\n 70|    o\n 60|    o\n 50| [249 chars]   t' != 
'Perc[25 chars]n100|          \n 90|          \n 80|         [349 chars] t  '

You need to add spaces to your empty lines. If you highlight the example chart you can see there are spaces after 100| but you immediately make a new line 100|\n 90
Screenshot 2024-08-26 090752

Entendido, muchas gracias por su ayuda.

1 Like