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
Related
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.
I think I should get True, but I am getting False and can not understand why. Thanks in advance for looking into this.
def game(name, mix, good, notgood, allv):
return str(name), tuple(mix), list(good), list(notgood), list(allv)
def create_game(name, mix):
return game(name, mix, gap(mix), gap(mix, 0), gap(mix, 1))
def gap(ltras, *args):
temp = []
if len(args) == 0:
temp.append("ABCD")
if len(args) == 1 and args[0] == 0:
temp.append("A")
if len(args) == 1 and args[0] == 1:
temp.append("AB")
temp.sort()
temp.sort(key=len)
return temp
def same(myobj):
return isinstance(myobj, type(game))
ourmix = ("T", "E", "S", "T")
p = create_game("ALFA", ourmix)
print(same(p))
The reason it's false is because 'game' is a function, whereas p is what the function 'game' returns, which is a tuple.
So essentially you are checking if a tuple (variable p) is an instance of function, which is what type(game) evaluates to.
If you wanted to use isinstance in this way, you could create a class called game and check isinstance(p,game), or in a function like you have it, isinstance(myobj,game).
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))
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...
I do have following decorator:
def memo(f):
"""Decorator that caches the return value for each call to f(args).
Then when called again with same args, we can just look it up."""
cache = {}
def _f(*args):
try:
return cache[args]
except KeyError:
cache[args] = result = f(*args)
return result
except TypeError:
# some element of args can't be a dict key
return f(args)
return _f
I need to write some tests to know if it works good. How can I test such decorator?
I only managed to write test for performance to know if it speeds up functions.
def test_memo(self):
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
#memo
def cached_fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return cached_fib(n - 1) + cached_fib(n - 2)
t0 = time.clock()
fib(20)
t = time.clock() - t0
t1 = time.clock()
cached_fib(20)
t2 = time.clock() - t1
self.assertGreater(t, t2)
Maybe it would be wise to test if it store some value in cache but I do not know how to achieve it in python. Any ideas?
The function decoarted should be called once for the same argument. Check that.
def test_memo__function_should_be_called_once_for_same_arg(self):
#memo
def f(arg):
f.call_count += 1
return arg
f.call_count = 0
self.assertEqual(f(1), 1)
self.assertEqual(f(1), 1)
self.assertEqual(f.call_count, 1)
self.assertEqual(f(2), 2)
self.assertEqual(f(2), 2)
self.assertEqual(f(2), 2)
self.assertEqual(f.call_count, 2)
BTW, In the cached_fib function, it should call cache_fib, not fib to take advantage of the memoization.