Scientific Computing with Python Projects - Budget App

Tell us what’s happening:

The last test of my Budget App is failing everytime and tells me to check the spacing. I did and everything seems to be well spaced. I saw a similar post in the forum but the solution found didn’t help in my case (not sure if doesn’t work or if I implemented it incorrectly).
My code so far is the following:

Your code so far

class Category:
    #Definir parametros da classe. Cada uma tem um nome, registo de despesas, quantia e levantamentos.
    def __init__(self,name):
        self.name = name
        self.ledger = []
        self.amount = 0
        self.withdrawals = 0
    #Verificar se existem fundos suficientes para proceder à ação pretendida
    def check_funds(self, amount):
        if amount > self.amount:
            return False
        else:
            return True

    #Funçao que permite depositar dinheiro nesta categoria, tendo como parametros amount e descrição (opcional)
    def deposit(self, amount, description = ""):
        self.ledger.append({"amount": amount, "description": description})
        self.amount += float(amount)

    #Função que permite levantar dinheiro da categoria, caso existam fundos suficientes. Caso contrário, nada acontece
    def withdraw(self, amount, description = ""):
        if not self.check_funds(amount):
            return False
        else:
            self.ledger.append({"amount": - amount, "description": description})
            self.amount -= float(amount)
            self.withdrawals += float(amount)
            return True
        
    #Receber o balanço dos depósitos com os levantamentos
    def get_balance(self):
        return self.amount

    #Transferir o budget(amount) de uma categoria para a outra e ajustar as quantias em cada um destes
    def transfer(self, amount, destination):
        if not self.check_funds(amount):
            return False
        else:
            message1 = f'Transfer to {destination.name}'
            self.withdraw(amount, message1)

            message2 = f'Transfer from {self.name}'
            destination.deposit(amount, message2)

            return True
    
    #Definir como queremos que a classe seja impressa atraves do método print
    def __str__(self):
        #Começar por definir o titulo
        name = str(self.name)
        stars_before = int((30-len(name))/2)
        stars_after = int(30-stars_before-len(name))
        title = stars_before * "*" + name + stars_after * "*"
        #Definir a listagem das várias transações, com as restrições de espaço
        full_text_l =[]
        full_text = ""
        for transaction in self.ledger:
            listing = str(transaction).replace('}','').replace('{','')
            split_listing = listing.split(",",1)
            descriptions = split_listing[1].split(": ")[1].replace("'","")
            if len(descriptions) > 23:
                descriptions= descriptions[:23]
    
            amounts = split_listing[0].split(": ")[1].replace("'","")
            if "." not in amounts:
                amounts = amounts + ".00"
            else:
                digits = amounts.split(".")
                decimal = digits[1]
                inteiro = digits[0]
                if len(decimal) > 2:
                    decimal = decimal[0:2]
                    amounts = inteiro + "." + decimal
                elif len(decimal) == 1:
                    decimal = decimal + "0"
                    amounts = inteiro + "." + decimal
                if len(amounts) > 7:
                    amount = amount[-7,-1]
                
                


            full_text_l.append(descriptions + (30 - len(descriptions) - len(amounts)) * " " + amounts)
        
        for x in full_text_l:
            full_text += x + "\n"

        
            
        #Definir a ultima linha, com o total
        last_line = f'Total: {str(self.amount)}' 

        #Juntar tudo
        final = title + '\n' + full_text + last_line
        return final 

def create_spend_chart(categories):
    #Categories é uma lista de categorias
    #QUEREMOS APENAS IR BUSCAR OS WITHDRAWALS

    total_amount = 0
    percentage_amounts = {}

    #Associar o nome da categoria ao seus levantamentos e guardar a quantia total

    for category in categories:
        percentage_amounts[category.name] = category.withdrawals
        total_amount += category.withdrawals

    #Transformar a quantia bruta em percentagem
    percentage_amounts.update((x, round(y*100/total_amount)) for x, y in percentage_amounts.items())

    #Criar o gráfico
    output = ""
    output += "Percentage spent by category\n"
    p = 100
    while p >=0:
        output += str(p).rjust(3, " ") + "|"
        for x, y in percentage_amounts.items():
            if y >= p:
                output += " o "
            else:
                output += 3*" "
        output += "\n"
        p -= 10 
    output += 4*" " + (len(categories)*3+1)*"-" + "\n"
    max_len = len(max(percentage_amounts, key=len))
    i = 0
    while i < max_len:
        output += 4*" "
        for w in list(percentage_amounts.keys()):
          if i <= len(w)-1:
            output += " " + w[i] + " "
          else:
            output += 3*" "
        output += "\n"
        i = i + 1
    output += "\n"
    return output

Your browser information:

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

Challenge Information:

Scientific Computing with Python Projects - Budget App

If you hit F12 to open the devtools and look in the console you can see this error:

AssertionError: 
'Perc[34 chars]     \n 90|         \n 80|         \n 70|    o[320 chars]\n\n' != 
'Perc[34 chars]      \n 90|          \n 80|          \n 70|  [340 chars] t  '

Your output is first, and the expected output is second. Looks like you are missing a space at the end of your lines before the \n character and you end with two newlines instead of t and two spaces: 't

I hope this helps!

I messed around with the spaces before the \n and I got it solved, which is weird because I had already tried that before.
Thank you so much for your help!

1 Like