Problem with the lab tasks. need guidance

Tell us what’s happening:

I coded the following code for the budget app but it is showing that some tasks are not done yet. please help me find the problem.

These are the tasks that are incomplete:

16. Printing a Category instance should give a different string representation of the object.

  1. 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.

Your code so far

class Category:
    def __init__(self,name):
        self.name = name
        self.ledger = []

    def get_balance(self):
        balance = 0
        for item in self.ledger:
            balance += item['amount']

        return balance
    
    def check_funds(self,amount):
        if amount > self.get_balance():
            return False
        else:
            return True

    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': -1*amount, 'description': description})
            return True
        else:
            return False


    def transfer(self,amount,other):
        if self.check_funds(amount):
            self.withdraw(amount,f'Transfer to {other.name}')
            other.deposit(amount,f'Transfer from {self.name}')
            return True

        else:
            return False



    def __str__(self):
        l = len(self.name)
        prefix_=((30-l)//2)*'*'
        suffix_=(30-l-len(prefix_))*'*'
        line ='\n'+prefix_+self.name+suffix_
        for transaction in self.ledger:
            t = transaction
            amount =format(t['amount'],".2f")
            des = t['description']
            if len(des) <= 23:
                if len(str(amount)) <=7:
                    line += f"\n{des}{(23-len(des))*' '}{(7-len(str(amount)))*' '}{str(amount)}"
                else:
                    line += f"\n{des}{(23-len(des))*' '}{str(amount)[0:7]}"
            
            else:
                if len(str(amount)) <=7:
                    line += f"\n{des[0:23]}{(7-len(str(amount)))*' '}{str(amount)}"
                else:
                    line += f"\n{des[0:23]}{str(amount)[0:7]}"

            
            
        line += f"\nTotal: {self.get_balance()}\n"

        return line

def create_spend_chart(categories):
    
    line = 'Percentage spent by category'

    spent_amounts = []
    for category in categories:
        spent_amount = 0
        for transaction in category.ledger:
            t = transaction
            if t['amount'] < 0:
                spent_amount += abs(t['amount'])
        
        spent_amounts.append({'category': category.name,'amount':spent_amount})

    total = sum(spend['amount'] for spend in spent_amounts)

    percentages = []
    for spent in spent_amounts:
        per = spent['amount']*100/total
        percentages.append({'category':spent['category'],'%_spent':int((per//10)*10)})

    for y in range (100,-1,-10):
        line +=f"\n{(3-len(str(y)))*' '}{y}| "
        for item in percentages:
            if item['%_spent'] >= y:
                line += 'o  '
            else:
                line += '   '
        

    line += '\n    -'+ len(categories)*'---'

    n = 0
    while True:
        n += 1
        space_count = 0
        line += '\n     '
        for item in percentages:
            if len(item['category']) >= n:
                if n == 1:
                    line += item['category'][n-1].upper() + '  '
                else:
                    line += item['category'][n-1] + '  '
            else:
                line += '   '
                space_count += 1

        if space_count >= len(percentages):
            break

    return line

your representation starts and ends with a new line, was this asked?

you have a similar issues with the other failed tests

it worked for one task for printing the category. Thanks. :slight_smile:

I still cannot fix the other two tasks.

Hi @theva

Please post your updated code.

Happy coding

class Category:
    def __init__(self,name):

        self.name = name

        self.ledger = []



    def get_balance(self):

        balance = 0

        for item in self.ledger:

            balance += item ['amount' ]



        return balance



    def check_funds(self,amount):

        if amount > self.get_balance():

            return False

        else:

            return True



    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': -1 *amount, 'description': description})

            return True

        else:

            return False




    def transfer(self,amount,other):

        if self.check_funds(amount):

            self.withdraw(amount,f'Transfer to {other.name}')

            other.deposit(amount,f'Transfer from {self.name}')

            return True



        else:

            return False





    def  __str__(self):

        l = len(self.name)

        prefix =((30-l)//2) *' *'

        suffix =(30-l-len(prefix)) *' *'

        line = prefix+self.name+suffix

        for transaction in self.ledger:

            t = transaction

            amount =format(t ['amount' ],".2f")

            des = t ['description' ]

            if len(des) <= 23:

                if len(str(amount)) <=7:

                    line += f"  n{des}{(23-len(des)) *' '}{(7-len(str(amount))) *' '}{str(amount)}"

                else:

                    line += f"  n{des}{(23-len(des)) *' '}{str(amount) [0:7 ]}"

            

            else:

                if len(str(amount)) <=7:

                    line += f"  n{des [0:23 ]}{(7-len(str(amount))) *' '}{str(amount)}"

                else:

                    line += f"  n{des [0:23 ]}{str(amount) [0:7 ]}"



            

            

        line += f"  nTotal: {self.get_balance()}"



        return line
    def create_spend_chart(categories):
        line = 'Percentage spent by category'



        spent_amounts =  [ ]

        for category in categories:

            spent_amount = 0

            for transaction in category.ledger:

                t = transaction

                if t ['amount' ] < 0:

                    spent_amount += abs(t ['amount' ])

            

            spent_amounts.append({'category': category.name,'amount':spent_amount})



        total = sum(spend ['amount' ] for spend in spent_amounts)



        percentages =  [ ]

        for spent in spent_amounts:

            per = spent ['amount' ] *100/total

            percentages.append({'category':spent ['category' ],'% _spent':int((per//10) *10)})



        for y in range (100,-1,-10):

            line +=f"  n{(3-len(str(y))) *' '}{y}| "

            for item in percentages:

                if item ['% _spent' ] >= y:

                    line += 'o  '

                else:

                    line += '   '

            



        line += '  n    -'+ len(categories) *'---'



        n = 0

        while True:

            n += 1

            space_count = 0

            line += '  n     '

            for item in percentages:

                if len(item ['category' ]) >= n:

                    if n == 1:

                        line += item ['category' ] [n-1 ].upper() + '  '

                    else:

                        line += item ['category' ] [n-1 ] + '  '

                else:

                    line += '   '

                    space_count += 1



            if space_count >= len(percentages):

                break



        return line

        if amount > self.get_balance():

            return False

        else:

            return True



    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': -1*amount, 'description': description})

            return True

        else:

            return False




    def transfer(self,amount,other):

        if self.check_funds(amount):

            self.withdraw(amount,f'Transfer to {other.name}')

            other.deposit(amount,f'Transfer from {self.name}')

            return True



        else:

            return False





    def __str__(self):

        l = len(self.name)

        prefix_=((30-l)//2)*'*'

        suffix_=(30-l-len(prefix_))*'*'

        line = prefix_+self.name+suffix_

        for transaction in self.ledger:

            t = transaction

            amount =format(t['amount'],".2f")

            des = t['description']

            if len(des) <= 23:

                if len(str(amount)) <=7:

                    line += f"\n{des}{(23-len(des))*' '}{(7-len(str(amount)))*' '}{str(amount)}"

                else:

                    line += f"\n{des}{(23-len(des))*' '}{str(amount)[0:7]}"

            

            else:

                if len(str(amount)) <=7:

                    line += f"n{des[0:23]}{(7-len(str(amount)))*' '}{str(amount)}"

                else:

                    line += f"\n{des[0:23]}{str(amount)[0:7]}"



            

            

        line += f"\nTotal: {self.get_balance()}"



        return line
    def create_spend_chart(categories):
        line = 'Percentage spent by category'



        spent_amounts = []

        for category in categories:

            spent_amount = 0

            for transaction in category.ledger:

                t = transaction

                if t['amount'] < 0:

                    spent_amount += abs(t['amount'])

            

            spent_amounts.append({'category': category.name,'amount':spent_amount})



        total = sum(spend['amount'] for spend in spent_amounts)



        percentages = []

        for spent in spent_amounts:

            per = spent['amount']*100/total

            percentages.append({'category':spent['category'],'%\_spent':int((per//10)*10)})



        for y in range (100,-1,-10):

            line +=f"\n{(3-len(str(y)))*' '}{y}| "

            for item in percentages:

                if item['%\_spent'] >= y:

                    line += 'o  '

                else:

                    line += '   '

            



        line += '\n    -'+ len(categories)*'---'



        n = 0

        while True:

            n += 1

            space_count = 0

            line += '\n     '

            for item in percentages:

                if len(item['category']) >= n:

                    if n == 1:

                        line += item['category'][n-1].upper() + '  '

                    else:

                        line += item['category'][n-1] + '  '

                else:

                    line += '   '

                    space_count += 1



            if space_count >= len(percentages):

                break
        return line

Hi @theva

There are two ways you can format your code to make it easier to read and test:

  1. After you copy/paste your code into the editor, select it by dragging your cursor over it then click the (</>) button in the toolbar to automatically wrap your code in backticks. (You can click on the animated demo image below to enlarge it.)

  1. Manually add three backticks on a new line above your code and on a new line after your code. Note that a backtick is NOT the same as a single quote('). To find the backtick key on your keyboard, see this post.

To see changes to your post as you make them, you can click the (M+) button on the toolbar to bring up the rich text editor:

Happy coding

Hi @theva

To help you debug add the following code to the end of the editor:

food = Category('Food')
food.deposit(1000, 'initial deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.89, 'restaurant and more food for dessert')
clothing = Category('Clothing')
food.transfer(50, clothing)
print(food)

Happy coding

hi ,

I think the problem is with the create_spend_chart section. the tasks related to the printing of the instance is completed. the other two tasks are related to the spent_chart

Thank you

We can’t test with the updated code you posted because it is not formatted correctly. Please follow @Teller 's suggestion on how to do that.

Hi @theva

I reformatted your code above.

Looks like there is a spacing issue.

Happy coding

To help you debug the spacing issue, try testing like this:

food = Category('Food')
food.deposit(1000, 'initial deposit')
food.withdraw(10.15, 'groceries')
food.withdraw(15.89, 'restaurant and more food for dessert')
clothing = Category('Clothing')
food.transfer(50, clothing)
clothing.withdraw(25.19, 'shirt')
print(create_spend_chart([food,clothing]).replace(" ","."))