[Python] Why is my create_spend_chart output not matching the required format? [closed]

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I’m trying to solve a project where I build a Category class and a create_spend_chart function to create a text-based spend chart. My Category class methods (deposit, withdraw, transfer) seem to work fine.

    But when I run create_spend_chart, the formatting is wrong — the spacing and alignment don’t exactly match what the project requires.

    For example, my category names printed vertically are not perfectly aligned with the bars, and sometimes there are missing spaces.

    enter code here


    Here is my code:

    Here is my code:

    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 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}"[:7]
    items += f"{description:<23}{amount:>7}\n"
    total = f"Total: {self.get_balance():.2f}"
    return title + items + total


    def create_spend_chart(categories):
    total_spent = 0
    category_spending = []

    # Calculate total spent per category
    for category in categories:
    spent = sum(-entry["amount"] for entry in category.ledger if entry["amount"] < 0)
    category_spending.append({"name": category.name, "spent": spent})
    total_spent += spent

    # Calculate percentage spent per category
    for item in category_spending:
    percent = (item["spent"] / total_spent) * 100
    item["percent"] = int(percent // 10) * 10

    # Begin creating the chart
    chart = "Percentage spent by category\n"

    # Create the vertical chart with percentages from 100 to 0
    for i in range(100, -1, -10):
    line = str(i).rjust(3) + "|"
    for item in category_spending:
    if item["percent"] >= i:
    line += " o "
    else:
    line += " "
    chart += line + " \n"

    # Add the bottom border
    chart += " " + "-" * (len(categories) * 3 + 1) + "\n"

    # Add the category names vertically below the bar
    max_length = max(len(item["name"]) for item in category_spending)
    for i in range(max_length):
    line = " "
    for item in category_spending:
    if i < len(item["name"]):
    line += item["name"] + " "
    else:
    line += " "
    chart += line.rstrip() + "\n"

    return chart.rstrip("\n")


    # Example Usage
    food = Category("Food")
    clothing = Category("Clothing")
    entertainment = Category("Entertainment")

    food.deposit(1000, "Initial deposit")
    food.withdraw(150.25, "Groceries")
    food.withdraw(50.75, "Snacks")

    clothing.deposit(500, "Initial deposit")
    clothing.withdraw(150, "Jeans")

    entertainment.deposit(800, "Initial deposit")
    entertainment.withdraw(300, "Movies")

    print(create_spend_chart([food, clothing, entertainment]))

    Continue reading...

Compartilhe esta Página