Scientific Computing with Python Projects - Budget App

I am struggling to find the errors in my create_spend_chart function, I have tried o fix it but I am lost. Can someone please help me.

This is my code:

def create_spend_chart(categories):

    # calculating percent 
    p_dct = []
    for cate in categories: 
        total = 0
        p_amt = 0
        for i in range(len(cate.ledger)):
            nmbr = str(cate.ledger[i]["amount"])
            if "-" in nmbr:
                n = nmbr.split("-")
                p_amt += float(n[1])
            else:
                total+= float(nmbr)
        


        
        percenage = round((p_amt / total) * 100)
        round_p = (percenage // 10) * 10 
        if round_p > 100:
            round_p = 100
        #elif round_p == 0:
           # round_p = 10


        p_dct.append({"percenage": round_p, "description": cate.name})


    p_str = 'Percentage spent by category\n'
    y_axis = [100,90,80,70,60,50,40,30,20,10,0]

    # setting up string on the y_axis 
    for digit in y_axis:
        if len(str(digit))== 3:
            p_str+= str(digit).rjust(3) + '|'
        elif len(str(digit)) == 0:
            p_str += str(digit).rjust(3) + ' |'
        else:
            p_str += str(digit).rjust(3) + '|' 
        for i in range(len(p_dct)):
            num1 = p_dct[i]["percenage"]
            if num1 == digit:
                p_str += ' o '
            elif num1 >= digit:
                p_str += ' o '
            elif num1 < digit:
                p_str += '    '
        p_str+= '  \n'

    
    # formating categories

    d_len = (len(p_dct) * 3) + 1
    p_str += '    ' + ('-' * d_len) + '\n'

    str_lst = []
    for i in range(len(p_dct)):
        str_lst.append(p_dct[i]["description"])
    
    max_length = max(len(item) for item in str_lst)

    for i in range(max_length):
        p_str+= '   '
        for word in str_lst:
            if i < len(word):
                p_str += '  ' + word[i]

            else:
                p_str += '   '
        p_str += '\n'


    



    return p_str

The error:

FAIL: test_create_spend_chart (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-budget-app-1/test_module.py", line 102, in test_create_spend_chart
    self.assertEqual(actual, expected, 'Expected different chart representation. Check that all spacing is exact.')
AssertionError: 'Perc[35 chars]       \n 90|            \n 80|            \n [359 chars]  \n' != 'Perc[35 chars]     \n 90|          \n 80|          \n 70|   [339 chars] t  '
  Percentage spent by category
- 100|            
?               --
+ 100|          
-  90|            
?               --
+  90|          
-  80|            
?               --
+  80|          
-  70|            
-  60|            
-  50|            
-  40|            
-  30|            
-  20|            
-  10|     o     
?  ^      -
+  70|    o     
?  ^
+  60|    o     
+  50|    o     
+  40|    o     
+  30|    o     
+  20|    o  o  
+  10|    o  o  
-   0| 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  
?               -
+            t   : Expected different chart representation. Check that all spacing is exact.

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15

Challenge: Scientific Computing with Python Projects - Budget App

Link to the challenge:

I think:
the error you are having indicates that you have indentation (formatting) issues with your code. You can use the formatter to fix the python code.

Also, your ‘Category’ class is missing or not pasted. I cannot tell exactly if your code will work or not, because I don’t know the methods in your category class

Oh yes I didn’t post my full code just my function because that is what I’m struggling with. I passed all the other tests just the spacing on this one I’m confused.

This is the rest of my code

class Category:
    def __init__(self, name):
        self.ledger = [] # a list of dictionaries 
        self.name = name

    def deposit(self, amount, desc = ''):
        am = {"amount": amount, "description": desc}    
        self.ledger.append(am)

    def withdraw(self,amount, desc=''):
        if self.check_funds(amount):
            self.ledger.append({"amount": -amount, "description": desc})
            return True 
        return False 

    def get_balance(self):
        nums = []
        # appending to categ and nums at same time so you know which is minus and plus 
        for i in range(len(self.ledger)): #iteratring through each dict
            nums.append(self.ledger[i]["amount"])

        a = 0
        for n in nums:
            n = str(n)
            if "-" in n:
                x = n.split('-')
                a-= float(x[-1])
            else:
                a+= float(n)
        return a # returns total 

        
    def transfer(self, amount, cate):
        if self.check_funds(amount):
            self.ledger.append({"amount": -amount, "description": "Transfer to " + cate.name})
            cate.ledger.append({"amount": amount, "description": "Transfer from " + self.name})
            return True 
        return False
    
    def check_funds(self, amount):
        if float(amount) > float(self.get_balance()): # checking balance
            return False
        return True 
        
    
    def __str__(self):
        # title 
        star_str = ''
        x = len(self.name)
        stars_num = 30 - x # num of stars 
        if stars_num % 2 == 0:
            num = stars_num // 2
            star_str += '*' * num + self.name + '*' * num+ '\n'
        else:
            num = stars_num // 2
            star_str += '*' * num + self.name + '*' * (num + 1) +"\n"


        # deposit and withdraws
        categ = []
        amts = []
        for i in range(len(self.ledger)): #iteratring through each item
                categ.append(self.ledger[i]["description"])
                amts.append(self.ledger[i]["amount"])
                


        for (c, amt) in zip(categ, amts):
                cate_len = len(c) # takes into account all of the spaces in it 
                str_len = 30 - len(f"{amt:.2f}")-1 # extra space in between desc and amount - dont need to add a space later
                
                letter_count = 0
                new_c = ''
                if cate_len > str_len:
                    for letter in c:
                        letter_count += 1 
                        if letter_count == str_len:
                            new_c = c[:letter_count]
                            break
                    
                    adjust = 30 - len(new_c)
                    print(adjust)
                    star_str += new_c + f"{amt:.2f}".rjust(adjust)+ '\n'

                
                else: # if the amount if bigger 
                    star_str += c + f"{amt:.2f}".rjust(30-cate_len)+'\n'

            
        bal = self.get_balance()
        star_str+= 'Total: ' + str(bal)
                
        return star_str

1 Like

You can see how your incorrect line, in red, has two extra spaces. It shows you the correct format in green and the ? line shows -- indicating the incorrect two extra spaces.

1 Like

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