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
CodePudding user response:
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
CodePudding user response:
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