Scientific Computing with Python Projects - Budget App

Hi, guys!

I finished my code from the “Budget App”, but it keeps failing on the last test, which is from the function create_spend_chart.

I already counted all of the blank spaces, but I can not find out what is wrong.

The error which appears is >>> "Perc[77 chars]| \n 60| \n 50| \n [297 chars] t ’ != 'Perc[77 chars]| o \n 60| o \n 50| o \n [297 chars] t ".

My code is:

class Category:
    # Creating the attributes
    def __init__(self, category):
        self.category = category
        self.ledger = list() 
        
    # Printing the category
    def __str__(self):
        first_line = self.category.center(30, "*") 
        middle_line = ''
        total = 0
        for item in self.ledger:
            # Adding the spaces to 'description'             
            if len(item['description']) < 23:
                item['description'] = item['description'].ljust(23)
            else: 
                item['description'] = item['description'][0:23]
            # Adding the spaces to 'amount'
            item['amount'] = "{:.2f}".format(float(item["amount"]))
            if len(item['amount']) < 7:
                item['amount'] = item['amount'].rjust(7)
            else: 
                item['amount'] = item['amount'][0:7]
            middle_line += item['description'] + item['amount'] + '\n'
            total += float(item['amount'])
        total = "{:.2f}".format(total)
        return first_line + "\n" + middle_line + "Total: " + str(total)
            
    # Method GET BALANCE
    def get_balance(self):
        balance = 0
        for item in self.ledger:
            balance += float(item['amount'])
        return balance
        
    # Method CHECK FUNDS
    def check_funds(self, value):
        bal = self.get_balance()
        if value > bal:
            return False
        else: 
            return True
    
    # Method DEPOSIT    
    def deposit (self, value, desc=""):
        self.ledger.append({"amount": value, "description": desc})
    
    # Method WITHDRAW
    def withdraw (self, value, desc='' ):
        if self.check_funds(value) == True:
            self.ledger.append({"amount": value * -1, "description": desc})
            return True
        else:
            return False
    
    # Method TRANSFER
    def transfer (self, value, destiny):
        if self.check_funds(value) == True:
            self.withdraw(value, "Transfer to " + destiny.category)
            destiny.deposit(value, "Transfer from " + self.category)
            return True
        else:
            return False

    # Method GET WITHDRAWS
    def get_deposits_withdraws(self):
        total_spent = 0
        total_deposit = 0
        for item in self.ledger:
            item['amount'] = float(item['amount'])
            if item['amount'] < 0:
                total_spent += item['amount']
            elif item['amount'] > 0:
                total_deposit += item['amount']
        return total_spent, total_deposit


def create_spend_chart (categories):
    result = '''Percentage spent by category\n'''
    # Calculating the percentage 
    dict_percentage = {}
    names = []
    for item in categories:
        [t_spent, t_deposit] = item.get_deposits_withdraws()
        percentage = abs((t_spent * 100) / t_deposit)
        if percentage == 100:
            dict_percentage[item.category] = str(int(percentage))
        else:
            dict_percentage[item.category] = str(int(percentage))[0]
        names.append(item.category)
    # Making the table of percentage
    for count in range(100, -10, -10): 
        count = str(count)
        check = ''
        for item in dict_percentage:
            if dict_percentage[item] == '100' and count == '100':
                check += " o "
                check.rjust(3)
                dict_percentage[item] = item = str(int(dict_percentage[item]) - 10)[0]
            elif count != '100' and dict_percentage[item] == count[0]:
                check += " o "   
                dict_percentage[item] = item = str(int(dict_percentage[item]) - 1)
            else:
                check += '   '
        check += ' ' + '\n'  
        # Adding the spaces
        count = count.rjust(3)
        result += count + '|' + check
     # Adding the line of dashes
    dashes =  "-" * (len(dict_percentage) * 3) + '-'
    # Printing the categories
    x_axis = '' 
    maxi = max(names, key=len)
    for x in range(len(maxi)):
        nameString = '     '
        for name in names:
            if x >= len(name):
                nameString += '   '
            else:
                nameString += name[x] + '  '
        if (x != len(maxi) - 1):
            nameString += '\n'
        x_axis += nameString
    result += '    ' + dashes  + '\n' + x_axis
    return result
    

Could anyone help me, please? :pray:

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36

Challenge: Scientific Computing with Python Projects - Budget App

Link to the challenge:

Compare the expected table:

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  

to your output:

100|          
 90|          
 80|          
 70|          
 60|          
 50|          
 40|          
 30|       o  
 20|       o  
 10| o  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  

Per the spec you need to calculate the percentages spent in each category of the total spent. It looks like you are calculating the percent spent of the money in each category.

Thank you!

I fix the problem of the percentage, but it still not passing the test.

The error is >>> AssertionError: 'Perc[34 chars] \n 90| \n 80| \n 70| o[330 chars] t ’ != 'Perc[34 chars] \n 90| \n 80| \n 70| [340 chars] t ’

# CLASS ------------------------------------------------------------------------------------------------------------------------------------------------------------
class Category:
  
    # Creating the attributes
    def __init__(self, category):
        self.category = category
        self.ledger = list() 
        
    # Printing the category
    def __str__(self):
        first_line = self.category.center(30, "*") 
        middle_line = ''
        total = 0
        for item in self.ledger:
            # Adding the spaces to 'description'             
            if len(item['description']) < 23:
                item['description'] = item['description'].ljust(23)
            else: 
                item['description'] = item['description'][0:23]
            # Adding the spaces to 'amount'
            item['amount'] = "{:.2f}".format(float(item["amount"]))
            if len(item['amount']) < 7:
                item['amount'] = item['amount'].rjust(7)
            else: 
                item['amount'] = item['amount'][0:7]
            middle_line += item['description'] + item['amount'] + '\n'
            total += float(item['amount'])
        total = "{:.2f}".format(total)
        return first_line + "\n" + middle_line + "Total: " + str(total)
            
    # Method GET BALANCE
    def get_balance(self):
        balance = 0
        for item in self.ledger:
            balance += float(item['amount'])
        return balance
        
    # Method CHECK FUNDS
    def check_funds(self, value):
        bal = self.get_balance()
        if value > bal:
            return False
        else: 
            return True
    
    # Method DEPOSIT    
    def deposit (self, value, desc=""):
        self.ledger.append({"amount": value, "description": desc})
      
    # Method WITHDRAW
    def withdraw (self, value, desc='' ):
        if self.check_funds(value) == True:
            self.ledger.append({"amount": value * -1, "description": desc})      
            return True
        else:
            return False
    
    # Method TRANSFER
    def transfer (self, value, destiny):
        if self.check_funds(value) == True:
            self.withdraw(value, "Transfer to " + destiny.category)
            destiny.deposit(value, "Transfer from " + self.category)
            return True
        else:
            return False

    # Method GET WITHDRAWS
    def get_withdraws(self):
        total_spent = 0
        for item in self.ledger:
            item['amount'] = float(item['amount'])
            if item['amount'] < 0:
                total_spent += item['amount']
        return total_spent


# FUNCTION ------------------------------------------------------------------------------------------------------
def truncate(n):
    multiplier = 10
    return int(n * multiplier) / multiplier

def get_totals(categories):
    total = 0
    breakdown = []
    for category in categories:
        total += category.get_withdraws()
        breakdown.append(category.get_withdraws())
        print(total, breakdown)
    rounded = list(map(lambda x: truncate(x / total), breakdown))
    return rounded

def create_spend_chart (categories):
    # Getting the categories names
    result = '''Percentage spent by category\n'''
    # Calculating the percentage 
    percentage = get_totals(categories)
    # Making the table of percentage
    for count in range(100, -10, -10): 
        check = ''
        for perc in percentage:
            if (perc * 100) >= count:
                check += " o "
            else:
                check += '   '
        check += '\n'  
        # Adding the spaces
        count = str(count).rjust(3)
        result += count + '|' + check
     # Adding the line of dashes
    dashes =  "-" * (len(percentage) * 3) + '-'
    # Printing the categories
    names = []
    for item in categories:
        names.append(item.category)
    x_axis = '' 
    maxi = max(names, key=len)
    for x in range(len(maxi)):
        nameString = '    '
        for name in names:
            if x >= len(name):
                nameString += '    '
            else:
                nameString += name[x] + '  '
        if (x != len(maxi) - 1):
            nameString += '\n'
        x_axis += nameString
    result += '    ' + dashes + '\n' + x_axis
    return result
1 Like

Check the spacing. This is your current output:

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  

It worked!
Thank you!