Python 2.7 code does not give correct answer - python

For some reason it seems like the code doesn't deduct from the right object and only adds to the receiver in my code, how can I fix this so the receiver gets the right amount added to his balance
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.tamout = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
def transfer(self, name, c):
self.balance -= c
name += c
return name
David = BankAccount(400)
John = BankAccount(200)
print "David balance is", David.balance
print "john balance is", John.balance
John.transfer(David.balance, 20)
print John.balance
print David.balance
The result is
David balance is 400
john balance is 200
180
400
Shouldn't the last print be 420?

This should fix your issue
class BankAccount:
def __init__(self, balance):
self.balance = balance
self.tamout = 0
def withdraw(self, amount):
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
def transfer(self, receiver, c):
self.balance -= c
receiver.deposit(c)
return receiver
if __name__ == '__main__':
David = BankAccount(400)
John = BankAccount(200)
print "David balance is", David.balance
print "john balance is", John.balance
John.transfer(David, 20)
print John.balance
print David.balance
By using David instance and use the deposit method on it

Your current transfer function receives a copy of the receiver's balance, not the original property.
Try this instead:
def transfer(self, name, c):
self.balance -= c
name.balance += c
return name
John.transfer(David, 20)

Related

open bank problem, cant seem to figure out why my solution isnt passing one last test case

I am trying to solve a problem on DoSelect Platform..
Following is the problem statement
Sid, as a developer wants to contribute to the Open Bank Project. He wants to create functions for deposit money, withdraw money, add interest and apply bank charges (in some cases) for a bank account.
There is also a constraint of this type of account, that any time if an operation causes the account balance to be negative, the account balance is reinitialised with 100. For example, if the current balance is 40 and you want to withdraw 60, then as 40-60 is negative, after this operation, now the account has 100.
As he thinks himself a smart coder, he wants to create a single function for all these tasks. The function is "Transaction" and it takes at most two parameters "a" and "b". Based on which parameter(s) is given, it performs different tasks. But Sid has no idea about OOP concepts.
class Account:
function init (variable balance):
//init is the standerd python __init__(self, variables) method.
//it initializes the account with user given balance
member variable balance= balance
function transaction (variable a, variable b):
//a (if given) denotes the amount to be withdraw/deposit in the account.
//so add a to balance if a is positive, otherwise subtract (-a) from balance if a is negative.
//b (if given) denotes the interest rate to give/charge to the account based on its sign.
//so add b% of current balance (rounded to nearest integer) to the balance as an interest, if b is positive
//otherwise subtract (-b)% of currenct balance (rounded to nearest integer) to the balance as bank charge, if b is negative
//after each operation, take care that, any time balance goes to negative, make it as 100.
//if neither a nor b is given:
//do nothing
//if a is given but b is not given:
//add/subtract a to the balance, based on sign of a
//if a is not given and b is given:
//add/subtract b% of current balance to the balance, based on sign of b
//if both a and b are given:
//first add/subtract a to the balance, get the new balance, then add/subtract b% of the new balance to the new balance.
//everytime take care that, if balance goes to negative, reinitialize it with 100.
Following is what I did
class Account:
def __init__(self, balance):
self.balance = balance
#self.balance = 100
def transaction(self, a = 0, b = 0):
if a != 0 and b != 0:
self.balance += a
self.balance += round((self.balance) * (b / 100))
if self.balance < 0:
self.balance = 100
elif a != 0 and b == 0:
self.balance += a
if self.balance < 0:
self.balance = 100
elif a==0 and b != 0:
self.balance += round((self.balance) * (b / 100))
if self.balance < 0:
self.balance = 100
else:
pass
return self.balance
def get_balance(self):
return self.balance
When I verify on the platform, it successfully verifies on the test case. However, when I try to submit it, it fails on 1 test case. DoSelect platform don't show what test cases they used to verify, so I cant figure it out.
As I said in my comment: Account(0).transaction(-1, 10) gives 100 with your solution. The task says to reinitialize the balance to 100 every time it goes to negative. If you apply this rule to every single step, the result should be 110 (0 -> -1 -> 100 -> 110).
I don't see the need for the different if-combinations for a and b. This is the moment when a developer has to translate the requirements into meaningful code. And the method get_balance is not needed, you can access the attribute directly.
class Account:
def __init__(self, balance):
self.balance = balance
if self.balance < 0:
self.balance = 100
def transaction(self, a=0, b=0):
self.balance += a
if self.balance < 0:
self.balance = 100
self.balance += round(self.balance * (b / 100))
if self.balance < 0:
self.balance = 100
account = Account(0)
account.transaction(-1, 10)
print(account.balance)
A "normal" programmer would create a method for the handling of if self.balance < 0, but since Sid has no idea about OOP concepts I just duplicated the code. With OOP the code for the class could be:
class Account:
def __init__(self, balance):
self.balance = balance
self.adjust_balance()
def adjust_balance(self):
if self.balance < 0:
self.balance = 100
def transaction(self, a=0, b=0):
self.balance += a
self.adjust_balance()
self.balance += round(self.balance * (b / 100))
self.adjust_balance()
With some more experience a programmer might use a property for the balance.
class Account:
def __init__(self, balance):
self._balance = balance
#property
def balance(self):
return self._balance
#balance.setter
def balance(self, value):
self._balance = value
if self._balance < 0:
self._balance = 100
def transaction(self, a=0, b=0):
self.balance += a
self.balance += round(self.balance * (b / 100))

How to update values within class

I'm trying to write a class separate from the main class and I want it to keep track of balance and number of items I buy coming from the main class. However, I'm having trouble updating the Num and balance every time I make a transaction and it keeps giving me 0 and 2000 when I print balance and num.
class Wallet:
def __init__(self, Num = 0, balance = 2000):
self.Num = Num
self.balance = balance
def addNum(self, c, d):
if d > self.balance:
return print(f'You have insufficient balance to buy {c}')
else:
self.balance -= d
self.Num += c
return Wallet().print()
def print(self):
print(f'You have {self.Num} of {self.balance}')
Wallet().addNum(3, 30)
Replace Wallet().print() with self.print(), otherwise you are creating a brand new Wallet every time you try to print it.

Trying to create a checking account class but running into issues

Write a class named “CheckingAccount” that contains the current
balance of the account (an int) and the following methods:
init - takes a “balance” parameter to initialize the data (balance)of the object. Remember, the method init is implemented as
___init__.
withdraw - takes an input parameter “amount” and modifies the data by reducing the balance. If “amount” results in an overdraw,subtract
an extra 20 dollars. This method should return the balance.
deposit - takes an input parameter “amount” and modifies the data by increasing the balance by “amount”.
I'm trying to do the above problem but I'm kind of lost and this is the best I've got so far (updated code today):
# write your code here
class CheckingAccount:
balance = 0
amount = 0
def __init__(self, balance = 0):
self.balance = balance
def withdraw(self, amount = 0):
if self.amount > self.balance:
self.balance -= 20
else:
self.balance -= 1
def deposit(self, amount = 0):
self.amount += amount
return amount
an = CheckingAccount(80)
an.withdraw(40)
print("Your old balance was {}. Your new balance is now {}.".format(an.balance))
I'm getting closer but my old balance shows as 79 instead of 80 and my new balance shows as 0 when I think I was expecting 40. I feel like I'm missing something.
class CheckingAccount:
balance = 0
oldbalance = 0
#amount = 0
def __init__(self, balance = 0):
self.balance = balance
def withdraw(self, amount = 0):
self.oldbalance = self.balance
if amount < self.balance:
self.balance -= amount
print("Amount withdrawn {}".format(amount))
else:
self.balance -= amount + 20
print("Amount withdraw ${} with penalty of $20".format(amount))
def deposit(self, amount = 0):
self.oldbalance = self.balance
self.balance += amount
return amount
an = CheckingAccount(80)
an.withdraw(10)
print("Your old balance was {}. Your new balance is now {}.".format(an.oldbalance, an.balance))

Python ATM, issues with simple subtraction?

This was my first experiment using Python classes and not sure why it doesn't withdrawal (subtract) from the balance. Any idea what I did wrong?
# ATM class with all functions
class ATM:
def __init__(self, balance, interest=0.1):
self.balance = balance
self.interest = interest
self.transactions = []
def check_balance(self): # checks balance
return f"Your balance is: ${self.balance}"
def deposit(self, amount): # deposits to balance
self.balance += amount
print(f"Deposit amount: {amount}")
return self.balance
def check_withdrawal(self, amount): # checks balance to see if we can withdraw
if self.balance - amount > 0:
return True
else:
print('Not enough funds to withdraw.')
def withdraw(self, amount): # *withdraws $$$$$$$$*
if self.balance - amount:
return f"You have withdrawn ${amount}"
# testing
checking_account = ATM(50000)
print(checking_account.check_balance())
print(checking_account.check_withdrawal(900))
print(checking_account.withdraw(900))
print(checking_account.check_balance())
def withdraw(self, amount): # *withdraws $$$$$$$$*
if self.balance - amount:
self.balance = self.balance - amount
return f"You have withdrawn ${amount}"
change your withdraw function, as you are not saving the deducted amount to your balance

Error checking inside a class

I'm supposed to create an Account class which uses some of the functions defined in the class above it. I'm having trouble with error checking in my withdraw class.
def withdraw(self, amount):
if amount > self.money:
return 'Error'
self.money -= amount
>>> a = Money(5,5)
>>> b = Money(10,1)
>>> acct1 = Account('Andrew', a)
>>> print(acct1)
Andrew's account balance is $5.05
>>> c = Money(3,50)
>>> acct1.deposit(c)
>>> print(acct1)
Andrew's account balance is $8.55
>>> acct1.withdraw(b)
>>> print(acct1)
Andrew's account balance is $-2.54
The output should be Error, but instead it just calculates and gives me back a negative balance.
The entire code is here:
class Money:
def __init__(self, dollars = 0, cents = 00):
'constructor'
self.dollars = dollars
self.cents = cents
if self.cents > 99:
self.dollars += 1
self.cents = self.cents - 100
def __repr__(self):
'standard representation'
return 'Money({}, {})'.format(self.dollars,self.cents)
def __str__(self):
'returns a string representation of ($dollars.cents)'
if self.cents < 10:
return '${}.0{}'.format(self.dollars, self.cents)
else:
return '${}.{}'.format(self.dollars, self.cents)
def __add__(self, new):
'Adds two money objects together'
d = self.dollars + new.dollars
c = self.cents + new.cents
return Money(d,c)
def __sub__(self, new):
'Subtracts two money objects'
d = self.dollars - new.dollars
c = self.cents - new.cents
return Money(d,c)
def __gt__(self, new):
'computes greater then calculations'
a = self.dollars + self.cents
b = new.dollars + new.cents
return a > b
class Account:
def __init__(self, holder, money = Money(0,0)):
'constructor'
self.holder = holder
self.money = money
def __str__(self):
return "{}'s account balance is {}".format(self.holder, self.money)
def getBalance(self):
return self.money
def deposit(self, amount):
self.money = self.money + amount
def withdraw(self, amount):
if amount > self.money:
return 'Error'
self.money -= amount
Actually it is because you don't compute the "balance" inside your __gt__ correctly.
The dollars should be multiplied by 100:
def __gt__(self, new):
a = self.dollars * 100 + self.cents
b = new.dollars * 100 + new.cents
return a > b
Optional: Instead of returning 'Error' you should consider raising an Exception:
def withdraw(self, amount):
if amount > self.money:
raise ValueError('Not enough money')
self.money -= amount

Categories