Hello, I can’t pass through two instructions. Can anybody help?
Project title: Build a Budget App
Course: Scientific Computing with Python
Instructions:
23. create_spend_chart chart should have each category name written vertically below the bar. Each line should have the same length, each category should be separated by two spaces, with additional two spaces after the final category.
24. create_spend_chart should print a different chart representation. Check that all spacing is exact. Open your browser console with F12 for more details.
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
return False
def get_balance(self):
return sum(item['amount'] for item in self.ledger)
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 self.get_balance() >= amount
def __str__(self):
title = f'{self.name:*^30}\n'
table = ''
for item in self.ledger:
table += f'{item["description"][:23]:23}{item["amount"]:>7.2f}\n'
total = f'Total: {self.get_balance():.2f}'
return title + table + total
def create_spend_chart(categories):
# total spending - all categories
total_spent = sum(sum(-item['amount'] for item in category.ledger if item['amount'] < 0) for category in categories)
# percentage spent by each category
percentages = [
math.floor(sum(-item['amount'] for item in category.ledger if item['amount'] < 0) / total_spent * 10) * 10 for category in categories]
chart = 'Percentage spent by category\n'
# percentage column
for i in range(100, -1, -10):
line = f'{i:>3}| '
for percent in percentages:
line += 'o ' if percent >= i else ' '
chart += line + '\n'
# horizontal line
chart += ' ' + '-' * (len(categories) * 3 + 1) + '\n'
# category names vertically
max_len = max(len(category.name) for category in categories)
for i in range(max_len):
line = ' '
for category in categories:
line += (category.name[i] + ' ') if i < len(category.name) else ' '
chart += line.rstrip() + '\n'
return chart.rstrip()
# Testing
food = Category('Food')
clothing = Category('Clothing')
entertainment = Category('Entertainment')
categories = [food, clothing, entertainment]
food.deposit(500, 'my first deposit')
food.withdraw(250, 'groceries')
food.transfer(50, entertainment)
food.withdraw(50, 'eating out')
clothing.deposit(500, 'deposit')
clothing.withdraw(250, 'new dress')
clothing.withdraw(50, 'hiking shoes')
print(food)
chart = create_spend_chart(categories)
print(chart)