Budget App Python Help

I am working on the Budget App project for Python Certification and have written all the required code. But, I am not able to pass two test cases, one bring related to rounding off the percentage, and another failure is related to alignment when we print the ledger which for some reason appears for only that particular test case. My code is as follows:

class Category:
	def __init__(self, name):
		self.name = name
		self.ledger = []
	def deposit(self, amount, des = ""):
		self.ledger.append({"amount": amount, "description": des})
	def withdraw(self, amount, des = ""):
		if self.check_funds(amount):
			self.ledger.append({"amount": -amount, "description": des})
			return True
		else:
			return False
	def get_balance(self):
		bal = 0
		for i in self.ledger:
			bal += i["amount"]
		return bal
	def transfer(self, amount, cat):
		if self.check_funds(amount):
			self.ledger.append({"amount": -amount, "description": "Transfer to " + cat.name})
			cat.ledger.append({"amount": amount, "description": "Transfer from " + self.name})
			return True
		else:
			return False
	def check_funds(self, amount):
		if self.get_balance() < amount:
			return False
		else:
			return True
	def __str__(self):
		total = 0
		led = self.name.center(30, "*")
		led += "\n"
		for i in self.ledger:
			des = i["description"]
			des = des[:23]
			while len(des) < 23:
				des += " "
			led += des
			amt = i["amount"]
			amt = "{:.2f}".format(amt)
			amt = amt[:7]
			total += float(amt)
			led += amt
			led += "\n"
		led += "Total: " + "{:.2f}".format(total)
		return led
def create_spend_chart(arr):
	expen = 0
	mon = []
	for i in arr:
		catexpen = 0
		for j in i.ledger:
			if j["amount"] < 0:
				expen += j["amount"]
				catexpen += j["amount"]
		mon.append(catexpen)
	percent = []
	for i in mon:
		percent.append(round((i / expen * 100) / 10) * 10)
	graph = "Percentage spent by category\n"
	num = 100
	while num >= 0:
		graph += str(num).rjust(3) + "| "
		for i in percent:
			if i >= num:
				graph += "o  "
			else:
				graph += "   "
		graph += "\n" 
		num -= 10
	graph += "    "
	num = len(arr)
	graph += "-" * (num * 3 +1)
	graph += "\n"
	graph += "     "
	high = 0
	for i in arr:
		if len(i.name) > high:
			high = len(i.name)
	for i in arr:
		while len(i.name) != high:
			i.name += " "
	for i in range(high):
		for j in arr:
			graph += j.name[i] + "  "
		graph += "\n" + "     "
	return graph

I get the following output when I run it in Replit:

973.96
*************Food*************
initial deposit        1000.00
groceries              -10.15
restaurant and more foo-15.89
Transfer to Clothing   -50.00
Total: 923.96
***********Clothing***********
Transfer from Food     50.00
                       -25.55
Total: 24.45
Percentage spent by category
100|          
 90|          
 80|          
 70| o        
 60| o        
 50| o        
 40| o        
 30| o        
 20| o  o     
 10| o  o  o  
  0| o  o  o  
    ----------
     F  C  A  
     o  l  u  
     o  o  t  
     d  t  o  
        h     
        i     
        n     
        g     
     
.F...F.....
======================================================================
FAIL: test_create_spend_chart (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-budget-app/test_module.py", line 94, in test_create_spend_chart
    self.assertEqual(actual, expected, 'Expected different chart representation. Check that all spacing is exact.')
AssertionError: 'Perc[170 chars] 10| o  o  o  \n  0| o  o  o  \n    ----------[211 chars]    ' != 'Perc[170 chars] 10|    o  o  \n  0| o  o  o  \n    ----------[204 chars] t  '
  Percentage spent by category
  100|          
   90|          
   80|          
   70|    o     
   60|    o     
   50|    o     
   40|    o     
   30|    o     
   20|    o  o  
-  10| o  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  
?               -
+            t  -       : Expected different chart representation. Check that all spacing is exact.

======================================================================
FAIL: test_to_string (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-budget-app/test_module.py", line 83, in test_to_string
    self.assertEqual(actual, expected, 'Expected different string representation of object.')
AssertionError: '****[46 chars]     900.00\nmilk, cereal, eggs, bac-45.67\nTr[38 chars]4.33' != '****[46 chars]      900.00\nmilk, cereal, eggs, bac -45.67\n[41 chars]4.33'
  *************Food*************
- deposit                900.00
+ deposit                 900.00
?                        +
- milk, cereal, eggs, bac-45.67
+ milk, cereal, eggs, bac -45.67
?                        +
- Transfer to Entertainme-20.00
+ Transfer to Entertainme -20.00
?                        +
  Total: 834.33 : Expected different string representation of object.

----------------------------------------------------------------------
Ran 11 tests in 0.021s

FAILED (failures=2)

I am not able to figure out why am I getting an alignment problem with only one test case and also I can’t think of anything about how to resolve the rounding off the percentage problem. It would be much appreciated if you helped.

To avoid the rounding error don’t use round() but instead think about a way to always round down to the nearest 10 - aka “losing” the last digit.

Second just add a space.

- deposit                900.00
+ deposit                 900.00
?                        +
- milk, cereal, eggs, bac-45.67
+ milk, cereal, eggs, bac -45.67
?                        +
- Transfer to Entertainme-20.00
+ Transfer to Entertainme -20.00
?                        +

I think you misinterpreted me for the second one. I meant to say that the problem with the spacing is in only that test case and no other similar test cases(if they exist), and if I add a space, then the other similar test cases will probably produce wrong output. But anyways I managed to fix it by using rjust(7) on the numbers.

For the first one, the output I got made the most sense to me because my output calculated the percentages as 10, 70, and 20 respectively which adds up to 100 , but the expected output of the test case wants it to be 0, 70, and 20 which only adds up to 90. So, I don’t see anything to do in this case and maybe (just maybe) the expected output is wrong. But still correct me if I am going wrong somewhere

“if” and “propably”?
How about you just test it, instead of speculating?
This is the very first thing you need to know as a programmer: Don’t spent hours speculating on something you can test in a minute.
It’s not a big program. And it’s highly unlikely this error will be limited to one testing case, given you got both long and short strings which produce the error.

Well the expected output is based on the description of the problem. And it states that you should “always round down to the nearest 10” - so 9% is turned into 0% for the chart.
This is just the given task and it’s on you to turn that into code. You are not supposed to program something other than the task, just because it might sound more reasonable to you. Because maybe your client had some reasoning for his/her decision to give you that specific task? And now you made them faulty code.

Hey, sorry for questioning the instructions itself and being dumb. I understand what you mean and fixed both the problems.
But there was another problem which I didn’t think of anything when I saw it because it was not visible when I ran the code in cmd and it is visible only in Replit. There is a dash (-) at the end of the graph and I don’t see a reason as to why it is there.

Below is the part of what Replit says when I run the code:

  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  
?               -
+            t  -       : Expected different chart representation. Check that all spacing is exact.

I have checked the test case and tried to replicate the exact commands and ran it in cmd and got following results:
image
As you can see there is no dash here

It’s usually helpful to post a link to your Replit.
The dash is from the unit-test and just as in the colorful quote from earlier, it’s indicating:

- your output
? [differences]
+ expected output

Or looking at the message itself:
'Perc[170 chars] 10| o o o \n 0| o o o \n ----------[211 chars] ' != 'Perc[170 chars] 10| o o \n 0| o o o \n ----------[204 chars] t '

While it takes some getting used to reading, it’s again “your output” first and then “expected output”. This both indicates the wrong rounding (because it’s from your earlier post) but also that at the end your code seems to produce more characters than expected - looking at the final line in your code, the dash propably indicates a line-break at the end of the chart followed by some spaces, because you add those even in the final loop, where the chart is actually finished.

Thank you for helping, I finally solved that challenge.

The dash were indeed indicating towards the line break and the spaces. I fixed it by using rstrip() method to remove the empty line and the spaces and I again added 2 spaces at the end because the expected output was case-sensitive and required 2 spaces at the end to accept the answer.

Once again thanks for your help and time

1 Like

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