class Category:
def __init__(self, name):
self.name = name
self.ledger = []
self.final_amount = 0
def __str__(self):
x = (30 - len(self.name))//2
Category_Str = f"{
'*'*x}{
self.name}{
'*'*x}"
if len(Category_Str) < 30:
Category_Str+='*'
Category_Str+='\n'
for i in self.ledger:
a = i['description']
b = str(f"{
i['amount']:.2f}")
Category_Str += f"{
a[:23]}{
' '*(30-len(a[:23])-len(b[:7]))}{
b[:7]}\n"
Category_Str += f"Total: {
self.final_amount}"
return Category_Str
def deposit(self, amount, description=''):
self.final_amount += amount
self.ledger.append(
{
'amount': amount,
'description':description
}
)
def withdraw(self, amount, description=''):
if self.check_funds(amount):
self.final_amount = self.final_amount - amount
self.ledger.append(
{
'amount': amount*-1,
'description':description
}
)
return True
else:
return False
def get_balance(self):
return self.final_amount
def transfer(self, amount, category):
if self.check_funds(amount):
self.withdraw(amount, f"Transfer to {
category.name}")
category.deposit(amount, f"Transfer from {
self.name}")
return True
else:
return False
def check_funds(self, a):
if self.final_amount - a >= 0:
return True
else:
return False
def create_spend_chart(categories):
a = []
b = []
d = []
for c in categories:
a.append(c.name.capitalize())
b.append(sum([i['amount'] for i in c.ledger[1:]]))
d.append(len(c.name.capitalize()))
cc = []
for aa in a:
cc.append(aa + (max(d) - len(aa))*' ')
b_sum = sum(b)
b = [(i*100//b_sum//10) for i in b]
str_1 = 'Percentage spent by category\n'
for i in range(0, 110, 10):
str_1 += f"{
100-(i):3d}|"
for j in b:
if (100-i) // 10 > j:
str_1 += " "
else:
str_1 += " o "
str_1 += ' \n'
str_1 += f"{
' '*4}{
'-'*(len(cc)*3+1)}\n"
# print('end')
for i in range(len(cc[0])):
str_1 += f"{
' '*4}"
for j in range(len(cc)):
str_1 += f" {
cc[j][i]} "
str_1 += ' \n'
return str_1[:-1]
空格和换行,对不上都不行