Tell us what’s happening:
where am i doing wrong please correct me i am stuck
Your code so far
# class Category:
# pass
# def create_spend_chart(categories):
# pass
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):
return sum(item['amount'] for item in self.ledger)
def transfer(self, amount, other_category):
if self.check_funds(amount):
self.withdraw(amount, f'Transfer to {other_category.name}')
other_category.deposit(amount, f'Transfer from {self.name}')
return True
return False
def check_funds(self, amount):
return self.get_balance() >= amount
def __str__(self):
title_line = self.name.center(30, '*')
ledger_lines = []
for item in self.ledger:
description = item['description'][:23]
amount = f"{item['amount']:>7.2f}"
ledger_lines.append(f"{description:<23}{amount}")
total_line = f"Total: {self.get_balance():.2f}"
return '\n'.join([title_line] + ledger_lines + [total_line])
def create_spend_chart(categories):
spending = {}
total_spent = 0
for category in categories:
spent = sum(item['amount'] for item in category.ledger if item['amount'] < 0)
spending[category.name] = -spent
total_spent += -spent
chart = "Percentage spent by category\n"
percentages = {cat: (spent / total_spent) * 100 for cat, spent in spending.items()}
highest_percentage = (max(percentages.values()) // 10 + 1) * 10
for i in range(int(highest_percentage), -1, -10):
row = f"{i:>3}| "
for category in categories:
if percentages.get(category.name, 0) >= i:
row += "o "
else:
row += " "
chart += row.rstrip() + " \n"
chart += " -" + "---" * len(categories) + "\n"
max_length = max(len(cat.name) for cat in categories)
for i in range(max_length):
row = " "
for category in categories:
if i < len(category.name):
row += category.name[i] + " "
else:
row += " "
chart += row.rstrip() + " \n"
return chart.rstrip()
food = Category("Food")
food.deposit(900, 'deposit')
food.withdraw(45.67, 'milk, cereal, eggs, bacon, bread')
clothing = Category("Clothing")
clothing.deposit(500, "Initial deposit")
clothing.withdraw(25.55, "Clothes")
entertainment = Category("Entertainment")
entertainment.deposit(200, "Initial deposit")
food.transfer(50, clothing)
print(food)
print()
print(clothing)
print()
print(entertainment)
print()
print(create_spend_chart([food, clothing, entertainment]))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36
Challenge Information:
Build a Budget App Project - Build a Budget App Project