Python Budget App -- create_spend_chart function is killing me

Hey all you smart, attractive people!

I’m hoping one of you can help me with this. As far as I can tell, the output of my function is identical to the test string (test_create_spend_chart for reference), but it’s not passing. If there are other ways to optimise the function(s) below, also, I’d be happy to hear about those as well!

### Category method
def get_withdrawls(self):
        total = 0
        for item in self.ledger:
            if item["amount"] < 0:
                total+= item["amount"]
        return total
def truncate(n):
    multiplier = 10
    return int(n * multiplier) / multiplier

def getTotals(categories):
    total = 0
    breakdown = []
    for category in categories:
        total += category.get_withdrawls()
    #Breakdown of spending rounded down to nearest 10th
    rounded = list(map(lambda x: truncate(x/total), breakdown))
    return rounded

def create_spend_chart(categories):
    res = "Percentage spent by category\n"
    i = 100
    totals = getTotals(categories)
    while i >= 0:
        cat_spaces = " "
        for total in totals:
            if total * 100 >= i:
                cat_spaces += "o  "
                cat_spaces += "   "
        res+= str(i).rjust(3) + "|" + cat_spaces + ("\n")
    dashes = "-" + "---"*len(categories)
    names = []
    x_axis = ""
    for category in categories:

    maxi = max(names, key=len)

    for x in range(len(maxi)):
        nameStr = '     '
        for name in names:
            if x >= len(name):
                nameStr += "   "
                nameStr += name[x] + "  "
        nameStr += '\n'
        x_axis += nameStr

    res+= dashes.rjust(len(dashes)+4) + "\n" + x_axis
    return res

Thanks a lot!

i think the problem might be that you add a next line in the last row of nameStr.
Not sure if it’s faster but you could change the while loop to a for loop which makes it easier to read in my opinion. for i in range(start, end, step)


Thanks a lot! You just earned me my Python cert!