Tell us what’s happening:
I know it’s not pretty code, but visually the chart looks correct.
Not sure why i’m failing the last 2 tests.
Your code so far
import math
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
else:
return False
def transfer(self, amount, destination):
if self.check_funds(amount):
self.withdraw(amount, f'Transfer to {destination.name}')
destination.deposit(amount, f'Transfer from {self.name}')
return True
else:
return False
def get_balance(self):
balance = 0
for transaction in self.ledger:
balance += float(transaction['amount'])
return balance
def check_funds(self, amount):
return amount <= self.get_balance()
def __str__(self):
categ_name_length = len(self.name)
left_stars = (30 - categ_name_length) // 2
right_stars = 30 - categ_name_length - left_stars
title_line = f'*' * left_stars + self.name.capitalize() + f'*' * right_stars + '\n'
entries = ''
for transaction in self.ledger:
left_side = transaction['description'][:23].ljust(23, ' ')
right_side = '{:.2f}'.format(transaction['amount']).rjust(7, ' ')
entries += left_side + right_side + '\n'
categ_total = 'Total: ' + str(self.get_balance())
return title_line + entries + categ_total
def create_spend_chart(categories):
spendings = {}
for category in categories:
categ_spending = 0
for transaction in category.ledger:
if transaction['amount'] < 0:
categ_spending += transaction['amount']
spendings[category.name] = categ_spending
total_spending = sum(spendings.values())
for categ in spendings.keys():
spendings[categ] = math.floor(((spendings[categ] / total_spending) * 100) / 10) * 10
chart = 'Percentage spent by category\n'
for i in range(100, -1, -10):
chart += f'{str(i).rjust(3)}| '
for perc in spendings.values():
chart += 'o ' if i <= perc else ' '
chart += '\n'
chart += ' ' * 4 + '-' * (3 * len(spendings.keys()) + 1) + '\n'
line = ''
longest_name = max(len(name) for name in spendings)
for i in range(longest_name):
line += ' ' * 5
for name in spendings:
if i < len(name):
line += name[i] + ' '
else:
line += ' '
line += '\n'
chart += line
return chart.strip()
food = Category("Food")
food.deposit(1000, "deposit")
food.withdraw(500.00, "groceries")
clothing = Category("Clothing")
clothing.deposit(1000, "deposit")
clothing.withdraw(100.00, "buying new clothes")
auto = Category("Auto")
auto.deposit(1000, "deposit")
auto.withdraw(200.00, "fuel")
food.transfer(200, clothing)
categories = [food, clothing, auto]
chart_str = create_spend_chart(categories)
print(chart_str)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:147.0) Gecko/20100101 Firefox/147.0
Challenge Information:
Build a Budget App - Build a Budget App