Build a Budget App - Build a Budget App

Tell us what’s happening:

Please help me , i can’t pass 19,22,23 questions , I have tried the Read-Search-Ask method but can’t solve

Your code so far

from itertools import zip_longest
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(amount < 0 or not self.check_funds(amount)) :
            return False
        else :
            amount = -amount
            self.ledger.append({'amount': amount, 'description': description})
            return True
    
    def get_balance(self):
        balance = 0
        for list_ledger in self.ledger :
            balance += list_ledger['amount'] 
        return balance

    def transfer(self ,amount ,other_category ):

        if(self.withdraw(amount, f"Transfer to {other_category.name}")):
            other_category.deposit(amount, f"Transfer from {self.name}")
            return True
        else:
            return False
    
    def check_funds(self ,amount):
        balance = self.get_balance()
        if balance - amount < 0:
            return False
        else :
            return True
    
    def __str__(self):
        category = f"{self.name.center(30, '*')}\n"

        for list_ledger in self.ledger:
            if(len(list_ledger['description']) > 23):
                string = f"{float(list_ledger['amount']):.2f}"
                espace = 7 - len(string)
               
                category += f"{list_ledger['description'][:23]}{espace*' '}{float(list_ledger['amount']):.2f}\n"
            else:
                string = f"{float(list_ledger['amount']):.2f}"
                espace = 7 - len(string)
                nb_espace = 23 - len(list_ledger['description'])
                
                category += f"{list_ledger['description']}{' '*nb_espace}{espace*' '}{float(list_ledger['amount']):.2f}\n"
            
        category +=f"Total: {float(self.get_balance()):.2f}"
        return category

        
def create_spend_chart(categories):
    title = "Percentage spent by category"

    def total_spend(categories=categories):
        total = 0
        for categorie in categories:
            for i in categorie.ledger:
                if (i['amount'] < 0):
                    total -= i['amount']
        return total
    

    def calcul_percentage(categorie, total_spent):
        total = 0
        for i in categorie.ledger:
            if (i['amount'] < 0):
                total -= i['amount']
               
        result = (total / total_spent)*100
        result_final = (result // 10) * 10
        return result_final
    
    dict_percentage = {}

    for categorie in categories:
        dict_percentage[categorie.name] = calcul_percentage(categorie, total_spend())
    

    def trie(dicte):
        return dict(sorted(dicte.items(),key=lambda x: int(x[1]), reverse=True))
    
    trie_percentage = trie(dict_percentage)

    list_percentage = [i for i in range(100,-10,-10)]
    

    liste = {}
    j = 1

    for name, percentage in trie_percentage.items() :
        
        nb_zero = int(int(percentage)/10) +1
        # print(nb_zero)

        
        zero = (nb_zero+1)*'o'
        escape = (11 - nb_zero)*' '
        str_zero = escape + zero
        liste[f"liste{j}"] = []
        liste[f"liste{j}"].extend(list(str_zero))
        j+=1

    k = len(list(liste.keys()))
    after =""
    q = list(liste.values())
    

    for i in zip(list_percentage,*q):
        escape = 0
        escape= 3 - len(str(i[0]))
        
        start_schema = f"{escape*' '}{i[0]}| "
        ligne = ""
        for j in range(1, k+1):
            ligne += f"{i[j]}  " 
        
        after +=  start_schema + ligne + "\n"

    ligne_bas = f"    {'-'*k*3}-"

    liste_key = {}
    for i , content in enumerate(trie_percentage.keys(), start=0):
        
        liste_key[f"liste_key{i}"] = []
        liste_key[f"liste_key{i}"].extend(list(content))

    liste12 = sorted(list(trie_percentage.keys()) , key=len, reverse=True)
    liste123 = len(liste12[0])
    test = list(liste_key.values())
  
  
    text_bas1 = ""
    g = 0

    for i in zip_longest(*test):
        g += 1
        text_bas = ""
        for x in range(0,k):
            if i[x] is None:
                text_bas += '   '
            else:
                text_bas += f"{i[x]}  "
        if (g == liste123):
            text_bas1 += f"     {text_bas}"
        else:
            text_bas1 += f"     {text_bas}\n"

         
    return f"{title}\n{after}{ligne_bas}\n{text_bas1}"

food = Category('Food')
food.deposit(1000, 'deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.89, 'restaurant')
clothing = Category('Clothing')

food1 = Category('Food1')
food1.deposit(1000, 'deposit1')
food1.withdraw(10.15, 'groceries1')
food1.withdraw(15.89, 'restaurant1')
food1.transfer(50, clothing)




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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:146.0) Gecko/20100101 Firefox/146.0

Challenge Information:

Build a Budget App - Build a Budget App

I don’t think there is anything in the instructions about sorting?

Thank you , i delete the sorting method and the probleme resolve

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.