Build a Budget App - Build a Budget App

Tell us what’s happening:

Questions 23, 24, and 19 have me baffled. I have looked at the Discord posts, and believe I have fixed all the issues. Having difficulty reconciling the test console with my output; they seem from different programs.

Your code so far

>>>import datetime
import math
class Category:
    def __init__(self,name):
        self.name = name
        self.ledger = []
        self.total = 0.0
        self.spending = 0.0
        self.timestamp = datetime.datetime.now()
    def __str__(self):
        st = (f"{self.name:*^30}\n")
        for i in (self.ledger):
            st += f"{i['description']:<23.23}{i['amount']:>7.2f}\n"
        st += f"Total: {self.total:.2f}"
#        st += f"Spending: {self.spending:.2f}"
        return st

    def deposit(self,amount,description = ''):
        self.ledger.append({'amount': amount,'description': description}) 
        self.total += amount

    def withdraw(self,amount,description = ''):
        if amount <= self.total:
            self.ledger.append({'amount': -amount,'description': description})
            self.total -= amount
            self.spending += amount
            return True
        else:
            return False

    def get_balance(self):
        return(self.total)  
    def check_funds(self,amt): 
        if amt <= self.total:
            return True
        else: return False

    def transfer(self,amt,destination):
        if self.check_funds(amt) == True:
            self.withdraw(amt,f'Transfer to {destination.name}')
            self.spending -= amt
            destination.deposit(amt,f'Transfer from {self.name}')
            return True
        else: return False

def create_spend_chart(cats):
    num = len(cats) # number of cats
    tot =0  # total spending
    centile = 11 # number of rows to calc
    rowtext = "" # holds chars in row
    srtd = []
    srtj = 0
    for ind,item in enumerate(cats):
        tot += item.spending
        srtd.append([item.spending,ind,item.name])
# need to sort here
    srtdnu = bubble_sort(srtd)
    rowtext = f"Percentage spent by category\n"
    r = 10
    while r < 11:
        pc = r*10
        r -= 1
        rowtext += f"{pc:>3}|"
        for j in range (num):
#            print(((100.*srtdnu[j][0]/tot)//10)*10,(100.*srtdnu[j][0]//tot),pc)
            if ((100.*srtdnu[j][0]/tot)//10)*10 >= pc:
                rowtext += " o "
            else: rowtext += "   "
        rowtext += ' \n'
        if r < 0 : break
# rows in bottom part
    rowtext += '    '
    rowtext += num * '---'
    rowtext += f"-\n"

# places in rows
    cols = len(srtdnu)
#iterate over cols through maxlen
    maxlen = 0
    for nm in srtdnu:
        if len(nm[2]) >= maxlen: maxlen = len(nm[2])
# num columns and maxlen rows
    titles = [["" for col in range(num)] for row in range(maxlen)]
    for col in range(num):
        for row in range(maxlen):
            titles[row][col]=srtdnu[col][2][row:row+1]
            if len(titles[row][col]) == 0:
                titles[row][col] = ' '
    for row in range(maxlen):
        rowtext += '    '
        for col in range(num):
           rowtext += f" {titles[row][col]} "
        rowtext +=  " \n"
    
    return rowtext[:-1]

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        # Flag to detect if any swap happened
        swapped = False
        for j in range(0, n - i - 1):
            # Compare adjacent elements
            if arr[j] < arr[j + 1]:
                # Swap them if they are in the wrong order
                arr[j], arr[j + 1] = arr[j + 1], arr[j] # Python simultaneous assignment
                swapped = True
        # If no swaps occurred, the array is sorted, and we can stop
        if not swapped:
            break
    return arr 

food = Category('Food')
food.deposit(1000, 'initial deposit')
food.withdraw(10.15, 'groceries')
#food.withdraw(15.89, 'restaurant and more food for dessert')
#food.withdraw(47, 'lunches')
clothing = Category('Clothing')
food.transfer(250, clothing)
clothing.withdraw(100,'jacket')
auto = Category('Auto')
auto.deposit(750, 'qtrly deposit')
auto.withdraw(250, 'monthly payment')
auto.withdraw(25, 'fuel')
auto.withdraw(30, 'fuel')
business = Category('Business')
business.deposit(500, 'monthly deposit')
business.withdraw(250, 'retirement fund')
clothing.withdraw(25,'laundry')
#food.deposit(900,'deposit')
food.withdraw(45.67,'milk, cereal, eggs, bacon')
entertainment = Category('Entertainment')
#food.transfer(20, entertainment)
entertainment.deposit(200,'deposit')
entertainment.withdraw(1.00,'movies')
#entertainment.withdraw(100.50, 'basketball')
#invest = Category('investment')
#invest.deposit(500)
#print(food)
#print(entertainment)
#print(clothing)
#print(invest)
#print(clothing)
#print(auto)
#print(invest)
#create_spend_chart([food,clothing,auto,invest])
business.withdraw(200)
print(create_spend_chart([food,business,entertainment]))

Your browser information:

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

Challenge Information:

Build a Budget App - Build a Budget App

looking at the assertion error

AssertionError: 'Perc[74 chars] 70| o        \n 60| o        \n 50| o        [300 chars]    '
             != 'Perc[74 chars] 70|    o     \n 60|    o     \n 50|    o     [300 chars] t  '

and at the diff visible in the console:

did you change the order of the categories?

can you clarify which user story make you think you need to do this?

I’m not sure what you mean by order. I have tried a number of changes, a few resulting in improvements related to column spacing. But this one appears to tell me that my output row is off by a space to the left, but when I look at it in my console each ‘o’ looks centered in its column, as I believe is required. I have worked through rounding down to the nearest 10 rather that simply rounding, and testing properly so the output is arithmetically correct. I have gotten rid of extra spaces, based on what I learned from an earlier error message. But this has me buffaloed, and I believe this is the only problem I have. If this formatting issue were resolved, I think all three of my problem areas would go away. I admit to lack of experience with the question evaluator, and know I need to learn a lot more, but this one seems to be using a different set of data.

you are reordering the categories, they are passed to the function in an order, your graph have them in a different order

can you clarify which user story make you think you need to do this?

Yes, I reordered as a quick way to display them in descending order. But looking back, there is no user story. Let me try without re-ordering and see what happens.

I took out the sorting on the categories by simply copying the old sorted array from the original category data. Problem solved! A problem I created in complicating things, but I learned something new about lists and tuples. Thanks

1 Like