Tell us what’s happening:
I’m stuck on the create_spend_chart section of this project. As far as I can tell, the output from my code matches the spacing and formatting of the desired output. Any help would be appreciated!
Your code so far
#Category Class
class Category:
#Instantiate Objects
def __init__(self, category):
self.category = category
self.ledger = []
def __str__(self):
output = int((30 -len(self.category))/2) * '*'
output += self.category
output += int((30 -len(self.category))/2) * '*'
for i in range(len(self.ledger)):
output += f"\n{self.ledger[i]['description'][:23]}"
rounded = ('{:.2f}'.format(self.ledger[i]['amount']))[:7]
output += ((30 - len(self.ledger[i]['description'][:23])) - len(rounded)) * ' '
output += rounded
total = '{:.2f}'.format(self.get_balance())
output += f'\nTotal: {total}'
return str(output)
def deposit(self, amount, description = ""):
self.ledger.append({'amount': amount, 'description': description})
def check_funds(self,amount):
balance = self.get_balance()
if amount > balance:
return False
return True
def withdraw(self, amount, description = ""):
if self.check_funds(amount):
self.ledger.append({'amount': amount*-1, 'description': description})
return True
return False
def get_balance(self):
balance = 0
for i in range(len(self.ledger)):
balance += self.ledger[i]['amount']
return balance
def transfer(self, amount, destination):
if self.check_funds(amount):
destination.deposit(amount,f'Transfer from {self.category}' )
self.withdraw(amount, f'Transfer to {destination.category}')
return True
return False
#Create Spend Chart
def create_spend_chart(categories):
chart = 'Percentage spent by category\n'
data = []
index = 0
for cat in categories:
data.append([cat.category, 0])
for item in cat.ledger:
if item['amount'] <= 0:
data[index][1] += item['amount'] *-1
index += 1
total_spend = 0
for i in data:
total_spend += i[1]
for i in data:
i.append(round((i[1]/total_spend)*100,-1))
for y in range(100, -10 ,-10):
stry = str(y)
if y < 100:
stry = ' ' + stry
if y == 0:
stry = ' 0'
stry += '|'
chart += stry
for i in data:
chart += ' '
if i[2] >= y:
chart += 'o '
else:
chart += ' '
chart += ' \n'
chart += ' ' + (3*(len(data))+1) * '-'
longest = 0
for i in data:
if len(i[0]) > longest:
longest = len(i[0])
for x in range(longest):
chart += '\n '
for i in data:
try:
chart += i[0][x] + ' '
except IndexError:
chart += ' '
print(chart)
food = Category("Food")
clothing = Category("Clothing")
auto = Category('Auto')
food.deposit(1000, "deposit")
food.withdraw(500, "groceries")
clothing.deposit(1000, "deposit")
clothing.withdraw(200, "groceries")
auto.deposit(1000, "deposit")
auto.withdraw(100, "groceries")
create_spend_chart([food, clothing, auto])
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36
Challenge Information:
Build a Budget App Project - Build a Budget App Project