Tell us what’s happening:
My code fails the test_create_spend_chart. It says to check the spaces but I can see any differences.
I realize it may be the way I calculate the percentage. Should we consider the percentage over all the categories or over the categories called by the function create_spend_chart ?
Your code so far
def create_spend_chart(categories: list):
## return an error if more than 4 categories
if len(categories) > 4:
return "Error: Too many categories"
## Calculate the total spending and spending per category
total_spending = sum(sum(item['amount'] for item in category.ledger if item['amount'] < 0) for category in categories)
category_spending = {category.category_name: -sum(item['amount'] for item in category.ledger if item['amount'] < 0) for category in categories}
category_spending_list = list(category_spending.items())
## calculate the percentage spent in each category and store it in list of dictionnaries {"category_name" : "", "categoty_spendings" : float}
category_spending_pc = [(item[0], int(item[1])*(-100 / total_spending)) for item in category_spending_list]
#print(sorted_category_spending_pc)
chart_width = 4 + len(categories) * 3 + 1
chart_heigth = 12 + max(len(category) for category, _ in category_spending_pc)
#build the lines of the chart
my_string = ""
##____Title_____
title = "Percentage spent by category\n"
my_string += title
##____Body_____
for i in range(100,-1,-10):
my_string += str(i).rjust(3) + "|"
for _element in category_spending_pc:
if _element[1] >= i :
my_string += " o "
else:
my_string += " "
my_string_formatted = "{:<{}}".format(my_string, chart_width)
my_string = my_string_formatted + " \n"
##____Bottom_____
len_bottom_line =(3 * len(categories) + 1)
my_string +=" " * 4 + "-" * len_bottom_line + "\n"
max_len = max(len(category.category_name) for category in categories)
#print(f"maximum len of categories names : {max_len}")
##____Labels_____
for i in range(max_len):
my_string += " " * 5
#print(i)
for _element in category_spending:
if i < len(_element[0]):
my_string += _element[0][i] + " "
else:
my_string += " "
if i < max_len - 1:
my_string += "\n"
return my_string
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0
Challenge Information:
Scientific Computing with Python Projects - Budget App