Tell us what’s happening:
I can’t pinpoint the issue even after comparing my output with the sample. Can you review my code and let me know what’s wrong?
Your code so far
class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def deposit(self, amount, description=''):
self.ledger.append({'amount': amount, 'description': description})
def withdraw(self, amount, description=''):
if self.check_funds(amount):
self.ledger.append({'amount': -amount, 'description': description})
return True
return False
def get_balance(self):
balance = 0
for item in self.ledger:
balance += item['amount']
return balance
def transfer(self, amount, category):
if self.check_funds(amount):
self.withdraw(amount, f'Transfer to {category.name}')
category.deposit(amount, f'Transfer from {self.name}')
return True
return False
def check_funds(self, amount):
return amount <= self.get_balance()
def __str__(self):
title = self.name.center(30, "*") + "\n"
items = ""
for item in self.ledger:
description = item["description"][:23]
amount = f"{item['amount']:.2f}"
items += f"{description:<23}{amount:>7}\n"
total_line = f"Total: {self.get_balance():.2f}"
return title + items + total_line
def create_spend_chart(categories):
chart = ""
chart += "Percentage spent by category\n"
spents = []
for category in categories:
withdraw = 0
for item in category.ledger:
if item["amount"] < 0:
withdraw += item["amount"]
spents.append(withdraw)
total = sum(spents)
percents = [int(int(spent / total * 10) * 10) for spent in spents]
for percent in range(100, -1, -10):
chart += str(percent).rjust(3) + "| "
for item in percents:
if item >= percent:
chart += "o "
else:
chart += " "
chart += "\n"
chart += " --" + "-" * len(categories) * 3 + "\n"
max_len = max(len(category.name) for category in categories)
names = [category.name for category in categories]
for i in range(0, max_len):
chart += " "
for name in names:
if i < len(name):
chart += name[i] + " "
else:
chart += " "
if i < max_len - 1:
chart += "\n"
return chart
def main():
food = Category('Food')
food.deposit(1000, 'initial deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.89, 'restaurant and more food for dessert')
clothing = Category('Clothing')
food.transfer(50, clothing)
print(food)
print(create_spend_chart(list([food, clothing])))
main()
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36
Challenge Information:
Build a Budget App - Build a Budget App