Tell us what’s happening:
I can’t solve the final bit the output looks the same as the expected output (for the barchart)
create_spend_chart should print a different chart representation. Check that all spacing is exact.
Your code so far
class Category:
def __init__(self,name):
self.name = name
self.ledger = []
def deposit(self,amount,explaination=''):
if amount > 0:
self.ledger.append({'amount':amount,'description':explaination})
def withdraw(self,amount,explaination=''):
if amount > 0 and self.check_funds(amount):
self.ledger.append({'amount':-amount,'description':explaination})
return True
return False
def get_balance(self):
return sum(item['amount'] for item in self.ledger)
def transfer(self,amount,category):
if amount > 0 and self.check_funds(amount):
self.withdraw(amount, f"Transfer to {category.name}")
category.ledger.append({"amount": amount, "description": f"Transfer from {self.name}"})
return True
return False
def check_funds(self,amount):
return amount <= self.get_balance()
def __str__(self):
title = f"{self.name:*^30}\n"
items = ""
for item in self.ledger:
description = item['description'][:23].ljust(23)
amount = f"{item['amount']:>7.2f}"
items += f"{description}{amount}\n"
total = f"Total: {self.get_balance():.2f}"
return title + items + total
def create_spend_chart(categories):
title = "Percentage spent by category\n"
# 计算每个类别的支出百分比
percentages = []
for category in categories:
total = sum(item['amount'] for item in category.ledger)
spent = sum(item['amount'] for item in category.ledger if item['amount'] < 0)
percentage = int((abs(spent) / total * 100) // 10 * 10)
percentages.append((category.name, percentage))
# 绘制图表
chart = ""
for i in range(100, -1, -10):
chart += f"{i:3d}| "
for _, percentage in percentages:
chart += "o " if percentage >= i else " "
chart += "\n"
# 添加底部横线
chart += " -" + "---" * (len(categories))+ "\n"
# 添加类别名称
max_name_length = max(len(name) for name, _ in percentages)
for i in range(max_name_length):
chart += " "
for name, _ in percentages:
chart += f"{name[i] if i < len(name) else ' '} "
chart += "\n"
return title + chart.rstrip("\n")
if __name__ == "__main__":
food = Category("Food")
food.deposit(1000, "initial deposit")
food.withdraw(70.15, "groceries")
food.withdraw(15.89, "restaurant and more food for dessert")
clothing = Category('Clothing')
food.transfer(50, clothing)
print(food)
print(clothing)
print(create_spend_chart([food,clothing]))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
Challenge Information:
Build a Budget App Project - Build a Budget App Project