I am having difficulties understanding the concept of parameterized decorator and how it works. Could someone please explain how it works and what would the decorator base look like in the example below:
#base(10)
def sum(x,y):
return x+y
print(sum(1,2))
Code speaks more than a thousand words:
def int2base(x, base):
""" Converts int to string with given base representation.
Credit to #Alex Martelli on http://stackoverflow.com/questions/2267362/convert-integer-to-a-string-in-a-given-numeric-base-in-python"""
if x < 0: sign = -1
elif x == 0: return digs[0]
else: sign = 1
x *= sign
digits = []
while x:
digits.append(digs[x % base])
x //= base
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
def base(num):
def decorator(func):
def wrapper(*args):
return int2base(func(*args), num)
return wrapper
return decorator
def my_sum(num1, num2):
return num1 + num2
# using decorator syntax
#base(2)
def my_sum2(num1, num2):
return num1 + num2
print(my_sum(1,2))
print(my_sum2(1,2))
# decorating manually
decorator = base(2) # base acts kinda like factory method
my_sum2_manual = decorator(my_sum)
print(my_sum2_manual(1,2))
Related
def one(*args):
if len(args) == 0:
return 1
return args
def plus(*args):
first_number = args[1]
second_number = args[0]
sum = first_number + second_number
return sum
def two(*args):
if len(args) == 0:
return 2
return args
print(one(plus(two())))
the question is to do calculations by using functions and it contains 3 parts first number, operation, and the second number and the goal is to do the operation (second part) on those two numbers (first part and third part) for example one(plus(two())) should return 3
now here is the part I don't know how to do, plus() function is called with one argument two() one(plus(two())) I want to add a second argument the initial number (first number) to the function so plus() function is now called with two args like this plus(two(), 1).
Now plus(two()) is args[0] inside one() function how can I append 1 to that args[0] so that the function be called like this plus(two(), 1) to access it inside plus() and first_number = args[1] becomes valid
The code below implements a similar syntax to the example, but with slightly different argument structure. I think this way the logic is clearer.
The point is that I define plus as a partial function so that it "absorb" two to form a function that works as "add_two".
def plus(number):
def _plus(x):
return x + number
return _plus
def one(op=None):
if op is None:
return 1
return op(1)
def two(op=None):
if op is None:
return 2
return op(2)
one(plus(two()))
# 3
One idea is to have plus return a function that will be called afterward by one or two:
def one(*args):
if len(args) == 0:
return 1
elif len(args) == 1:
fn = args[0]
return fn(1)
else:
raise ValueError("Invalid number of arguments")
def two(*args):
if len(args) == 0:
return 2
elif len(args) == 1:
fn = args[0]
return fn(2)
else:
raise ValueError("Invalid number of arguments")
def plus(second_number):
def adder(first_number):
return first_number + second_number
return adder
Now:
>>> one(plus(two()))
3
>>> one(plus(one()))
2
>>> two(plus(one()))
3
>>> two(plus(two()))
4
And to simplify and DRY it:
def make_number(n):
def number_fn(fn=None):
if fn:
return fn(n)
else:
return n
return number_fn
def make_operator(operator):
def operator_wrapper(second_number):
def partial(first_number):
return operator(first_number, second_number)
return partial
return operator_wrapper
one = make_number(1)
two = make_number(2)
plus = make_operator(lambda a, b: a + b)
minus = make_operator(lambda a, b: a - b)
>>> two(minus(one()))
1
I am doing a task where I have a class Fractions which contains functions as to how I can add, subtract, multiply and divide the fractions. I am having trouble creating the add function which will be adding 2 fractions and this function must use the staticmethod. This is the code that I have written so far:
class Fraction:
def __init__(self,num1=0,num2=0):
self.num1=num1
self.num2=num2
def __str__(self):
while self.num1>self.num2:
a = self.num1//self.num2
b = self.num1 % self.num2
if self.num2==1:
return "%s"%(self.num1)
elif self.num1 % self.num2==0:
return "%s"%(self.num1/self.num2)
else:
return "%s+%s|%s"%(a,b,self.num2)
if self.num1==0:
return "0"
elif self.num1 or self.num2 < 0 and self.num1==self.num2:
return "-1"
elif self.num2==1:
return "%s"%(self.num1)
elif self.num1==self.num2:
return "1"
else:
return "%s|%s"%(self.num1,self.num2)
#staticmethod
def add(a,b):
a=Fraction(n,d)
b=Fraction(num,den)
if a.d == b.den and a.n<a.d or b.num<b.den:
return "%s|%s"%(a.n+b.num,a.d)
elif a.d != b.den:
return "%s|%s"%((a.n*b.den)+(a.d*b.num),(a.d*b.den))
I am facing trouble in trouble in the add function and I do not know how to make the function work.
For example:
Fraction.add(Fraction(1,4),Fraction(2,4))
>>> 3|4
Fraction.add(Fraction(1,5),Fraction(6,7))
>>> 1 + 2|35
This is what the output should look like. Could anyone guide me through the add function and how I can improve it using the staticmethod
If the arguments a and b are already Fraction objects, then you would use the attributes from them directly in your method:
#staticmethod
def add(a,b):
if a.num2 == b.num2 and (a.num1 < a.num2 or b.num1 < b.num2):
return "%s|%s"%(a.num1 + b.num1, a.num2)
elif a.num2 != b.num2:
return "%s|%s"%((a.num1 * b.num2) + (a.num2 * b.num1), (a.num2 * b.num2))
There were also a missing parenthesis in the first if clause.
add_digits2(1)(3)(5)(6)(0) should add up all the numbers and stop when it reaches 0.
The output should be 15
The below code works but uses a global variable.
total = 0
def add_digits2(num):
global total
if num == 0:
print(total)
else:
total += num
return add_digits2
The result is correct but needs to do the same thing without using the global variable.
One thing you could do is use partial:
from functools import partial
def add_digits2(num, total=0):
if num == 0:
print(total)
return
else:
total += num
return partial(add_digits2, total=total)
add_digits2(2)(4)(0)
You can just pass in *args as a parameter and return the sum
def add_digits2(*args):
return sum(args)
add_digits2(1, 3, 5 ,6)
You could also use a class, using the __call__ method to obtain this behavior:
class Add_digits:
def __init__(self):
self.total = 0
def __call__(self, val):
if val != 0:
self.total += val
return self
else:
print(self.total)
self.total = 0
add_digits = Add_digits()
add_digits(4)(4)(0)
# 8
add_digits(4)(6)(0)
# 10
though I still don't get why you would want to do this...
Really hard to say what they are after when asking questions like that but the total could be stored in a function attribute. Something like this
>>> def f():
... f.a = 3
>>> f()
>>> f.a
3
I tried to implement fractions using classes in python, but when I ran it,
it showed the error 'function gcd is not defined'. I can't seem to figure out how.
However, when I defined GCD outside the class it was working perfectly fine.
class frac:
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a%b)
def __init__(self, numer, denom):
if(denom == 0):
raise Exception("WTF")
else:
self.numer = numer
self.denom = denom
self.ratify()
def ratify(self):
g = gcd(self.numer, self.denom)
self.numer = self.numer/g
self.denom = self.denom/g
def add(self, b):
n,d = self.numer, self.denom
self.numer = n*b.denom + d*b.numer
self.denom = d*b.denom
self.ratify()
What is going wrong?
Your gcd method needs to look like:
def gcd(self, a, b):
if(b == 0):
return a
else:
return self.gcd(b, a%b)
How do I create the divide method in Python?
This is my code:
# Rational numbers
def gcd(bigger, smaller):
'''compute the greatest common divisor of two positive integers'''
#print(' in gcd ')
if not bigger > smaller :
bigger, smaller = smaller, bigger
while smaller != 0:
remainder = bigger % smaller
#print('gcd calc, big:{}, small:{}, rem:{}'.format(bigger, smaller, remainder))
bigger, smaller = smaller, remainder
return bigger
def lcm(a, b):
'''calculate the least common multiple of two positive integers'''
#print(' in lcm ')
return (a*b)//gcd(a,b)
class Rational(object):
'''Rational with numerator and denominator. Denominator defaults to 1'''
def __init__(self, numer, denom = 1):
#print('in constructor')
self.numer = numer
self.denom = denom
def __str__(self):
'''String representation for printing'''
#print(' in str ')
return str(self.numer) + '/' + str(self.denom)
def __repr__(self):
''' Used in the interpreter. Call __str__ for now'''
print(' in repr ')
return self.__str__()
def __add__(self, param_Rational):
'''Add two Rationals'''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom + \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
else:
print("Wrong type in addition method.")
raise(TypeError)
def __sub__(self, param_Rational):
'''Subtract two Rationals'''
#print(' in add ')
# find the lcm
the_lcm = lcm(self.denom, param_Rational.denom)
# multiply each numerator by the lcm, then add
numerator_sum = the_lcm*self.numer/self.denom - \
the_lcm*param_Rational.numer/param_Rational.denom
return Rational( int(numerator_sum), the_lcm )
def reduce_rational(self):
'''Return the reduced fraction value as a Rational'''
# find the gcd and divide numerator and denominator by it
the_gcd = gcd(self.numer, self.denom)
return Rational( self.numer//the_gcd, self.denom//the_gcd)
def __eq__(self, param_Rational):
'''Compare two Rationals for equalit and return a Boolean'''
reduced_self = self.reduce_rational()
reduced_param = param_Rational.reduce_rational()
return reduced_self.numer == reduced_param.numer and\
reduced_self.denom == reduced_param.denom
def __mul__(self, param_Rational):
''' Multiply two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.numer
denom_mul = self.denom*param_Rational.denom
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
else:
print("Wrong type in subtraction method")
raise(TypeError)
""" """
def __truediv__(self): # <-------- Here is where TypeError occurs #
''' Divide two Rationals '''
if type(param_Rational) == int:
param_Rational = Rational(param_Rational)
if type(param_Rational) == Rational:
#multiply
denom_zero_check = self.denom
second_denom_zero_check = param_Rational.denom
if denom_zero_check & second_denom_zero_check > 0:
numer_mul = self.numer*param_Rational.denom
denom_mul = self.denom*param_Rational.numer
return Rational(int(numer_mul),int(denom_mul))
else:
print("Denominator can't be zero.")
And I'm getting the error (location marked above):
TypeError: __truediv__() takes 1 positional argument but 2 were given
How do I fix this? I got the multiplication down but not the divide, should I use div or truediv? And do I need to use / in the actual div method?
How can __truediv__ only take one argument? You need two, self and the divisor. The same way your __mul__ __add__, and __sub__ needed a second argument.
def __truediv__(self, param_Rational):
# rest of your code
Instead of first printing an error message and then raising the error, you can use:
raise TypeError("Wrong type in addition method.")
Also, it might be usefull to check wether the demnominator is 0 or not in init(), and raise ZeroDivisionError if it is.
PS: 2/3 / 6/9 should equal 1/1 as 2/3=6/9=0.666...