This is my output from the code. Below are the suggestions:
21create_spend_chart should correctly show horizontal line below the bars. Using three - characters for each category, and in total going two characters past the final bar.
24 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.
Please update the message to include your code. The code was too long to be automatically inserted by the help button.
When you enter a code, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
import math
class Category:
def __init__(self, name):
self.name = name
self.ledger = []
def __str__(self):
title = f"{self.name:*^30}\n"
items = ""
total = 0
for item in self.ledger:
desc = item['description'][:23]
amount = item['amount']
items += f"{desc:<23}{amount:>7.2f}\n"
total += amount
output = title + items + "Total: " + str(total)
return output
def deposit(self, amount, description=""):
"""
Adds a deposit to the ledger.
:param amount: The amount deposited.
:param description: A brief description (optional).
"""
self.ledger.append({'amount': amount, 'description': description})
def withdraw(self, amount, description=""):
"""
Attempts to withdraw an amount from the budget.
:param amount: The amount to be withdrawn.
:param description: A brief description (optional).
:return: True if withdrawal is successful, False otherwise.
"""
if self.check_funds(amount):
self.ledger.append({'amount': -amount, 'description': description})
return True
return False
def get_balance(self):
"""
Returns the current balance in the category.
:return: Total balance after all deposits and withdrawals.
"""
return sum(item['amount'] for item in self.ledger)
def transfer(self, amount, destination_category):
"""
Transfers money from this category to another.
:param amount: Amount to transfer.
:param destination_category: Another Category instance.
:return: True if transfer was successful, False otherwise.
"""
if self.check_funds(amount):
self.withdraw(amount, f"Transfer to {destination_category.name}")
destination_category.deposit(amount, f"Transfer from {self.name}")
return True
return False
def check_funds(self, amount):
"""
Checks if there are sufficient funds for a transaction.
:param amount: The amount to check.
:return: True if enough funds, False otherwise.
"""
return amount <= self.get_balance()
def __str__(self):
"""
String representation of the Category object.
Displays the title line, each ledger item, and the total balance.
"""
# Title line centered with asterisks
title_line = f"{self.name:*^30}"
# Format each item in the ledger
formatted_items = []
for item in self.ledger:
desc = item['description'][:23].ljust(23)
amount = f"{item['amount']:>7.2f}"
formatted_items.append(f"{desc}{amount}")
# Total line
total_balance = f"Total: {self.get_balance():.2f}"
return "\n".join([title_line] + formatted_items + [total_balance])
def create_spend_chart(categories):
# Calculate total withdrawals per category
withdrawals = [sum(item['amount'] for item in cat.ledger if item['amount'] < 0) for cat in categories]
total_withdrawals = sum(withdrawals)
# Calculate percentage spent by category (rounded down to nearest 10)
percentages = [math.floor((w / total_withdrawals * 100)) if total_withdrawals != 0 else 0 for w in withdrawals]
# Build the vertical bar chart lines
chart_lines = []
for i in range(100, -1, -10):
line = f"{i:3d}| "
for percent in percentages:
line += "o " if percent >= i else " "
line += " " # Add two more spaces at the end for consistency
chart_lines.append(line)
# Create the horizontal line
dash_line = " " + "-" * (3 * len(categories) + 1)
# Format the category names vertically
max_len = max(len(cat.name) for cat in categories)
vertical_names = []
for i in range(max_len):
line = " "
for cat in categories:
line += cat.name[i] if i < len(cat.name) else " "
line += " "
line = line.rstrip() + " " # Ensure trailing two spaces
vertical_names.append(line)
# Final result
result = (
"Percentage spent by category\n" +
"\n".join(chart_lines) +
"\n" + dash_line +
"\n" + "\n".join(vertical_names)
)
return result
food = Category('Food')
food.deposit(900, 'deposit')
food.withdraw(100, 'milk')
clothing = Category('Clothing')
clothing.deposit(1000, 'initial deposit')
clothing.withdraw(200, 'shirts')
auto = Category('Auto')
auto.deposit(500, 'car funds')
auto.withdraw(300, 'tires')
print(create_spend_chart([food, clothing, auto]))[quote="pkdvalis, post:3, topic:750888, full:true"]
[quote="shivanshsharma30001, post:2, topic:750888"]
Open your browser console with F12 for more details.
[/quote]
Did you check this? It will have more details.
[/quote]