How to update values within class - python

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.

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))

A simplified 0/1 Knapsack problem with multiple items allowed in Python

I have a problem which is a simplified version of the knapsack problem. It goes like this. There is a store and we have a list of items in that store. Let's say like this,
Store has 2 types of products Normal products and limited products.
Product Class
class Product:
"""
A class to provide abstraction for products availabel in the system.
unless the product is a Limited_product its supply is infinite
"""
product_counter = 0
##### Part 1.1 #####
def __init__(self, name, price):
""" Constructor for initialization """
self.name = name
self.price = price
self.id = Product.product_counter
Product.product_counter += 1
def __str__(self):
""" returns a string representation of a product """
return "<{}> {} - {}$".format(self.id, self.name, self.price)
def __repr__(self):
""" represents the class object as a string """
return "PRODUCT <{}>".format(self.id)
Limited Product Class
class Limited_Product(Product):
"""
A child class of the parent Product class
Represents a Limited product where the quantity is depreceating
"""
##### Part 1.2 #####
def __init__(self, name, price, amount):
""" Constructor for initialization """
super().__init__(name, price)
self.amount = amount
def __str__(self):
""" returns a string representation of a limited product """
return "<{}> {} - {}$ ({} left)".format(self.id, self.name, self.price, self.amount)
def decrement_amount(self):
""" decrement the amount of available product """
self.amount -= 1
def get_amount(self):
""" returns the amount available from the product """
return self.amount
Now we are given a list of products and the maximum amount a customer can spend.
============================
Product - Price
A - 20$
B - 7$
C - 1$ (2 left)
============================
And we have to find out what is the minimum amount left after the customer buys a sequence from these items using both recursion as well as iteratively by completing the given two functions. These functions are given so I cannot write in a different method.
As an example:
>>> store.so_rich(45)
output - 1
You have 45 dollars to spend. The optimal solution is buying six B items and two C items. This will leave you with 45 - 7 * 6 - 1 * 2 = 1 dollars left. The least amount of money left is 1 since there is no way to spend all of the money. (although C’s price is 1$, you have purchased all of them already!)
>>> store.so_rich(61)
0
You have 61 dollars to spend. You can spend all of them by buying two A and three B (20 * 2 + 7 * 3 = 61). So the least amount of money left is 0.
The two functions that I wrote
def so_rich(self, money):
# suppose you haven't seen any product yet
# the only possible amount of money left is "money"
# this is a set to record the possible money left
left = set([money])
# get products
lst = list(self.warehouse.inventory.values())
print(str(lst))
for product in lst:
# a temporary set to save the updates of "left"
# you don't want to modify the set you're iterating through
tmp_left = set()
for m in left:
# update tmp_left
if type(product) != Limited_Product:
new_left = m
#new_left -= product.price
while product.price <= new_left:
print(new_left, product.name)
tmp_left.add(new_left)
new_left = new_left - product.price
else:
# handle limited product
new_left = m
product_count = product.amount
while product.price <= new_left and product_count > 0:
print(new_left, product.name)
tmp_left.add(new_left)
new_left = new_left - product.price
product_count -= 1
left = tmp_left
print(left)
return min(left)
def so_rich_recursive(self, money):
# get products
lst = list(self.warehouse.inventory.values())
def helper(lst, money):
# base case
if not lst:
return money
cur_min = money
product = lst[0]
if type(product) != Limited_Product:
tmp = money
while product.price < tmp:
cur_min = tmp
tmp -= product.price
print(cur_min, product.name)
else:
tmp = money
product_count = product.amount
while product.price <= tmp and product_count > 0:
cur_min = tmp
tmp -= product.price
product_count -= 1
print(cur_min, product.name)
money = money - cur_min
print("-----", money)
lst.pop(0)
return helper(lst, money)
return helper(lst, money)
I cannot understand why the above code written by me does not work. Can anyone help me, please?

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 2.7 code does not give correct answer

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)

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