the variables self.ledger
inside a class displays some deposits and withdraws in this way:
[{'amount': 50, 'description': 'Santa Claus arrived'}, {'amount': -12.5, 'description': 'Thiefs arrived'}]
The 2 methods withdraw
and deposit
append information into self.ledger
each time they're called.
Here is the function to get the balance:
def get_balance(self):
self.Alldeposited = sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
self.Allwithdrawn = abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
self.balance = self.Alldeposited - self.Allwithdrawn
return self.balance
Here is the function to get the percentage spent:
def percentage_spent(self):
self.Alldeposited = sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] > 0])
self.Allwithdrawn = abs(sum([Transaction["amount"] for Transaction in self.ledger if Transaction["amount"] < 0]))
Percentage = round(((self.Allwithdrawn*100)/self.Alldeposited),-1)
return Percentage
As you can see the code is repetitive, how could I make it less repetitive?