Issue
For school I have to finish some exercises. I keep getting this error:
TypeError <lambda> () missing 1 required positional argument: 'f2'
and I have no idea what I'm doing wrong. This code is supposed to do multiple things, namely:
- Function
OR
takes two functions as inputs and returns alambda
which, given one input, applies both functions to such input and computes the 'or' of the results. - Function
OR
takes two functions as inputs and returns alambda
which, given one input, applies both functions to such input and computes the 'or' of the results. - Function
OR
takes two functions as inputs and returns alambda
which, given one input, applies both functions to such input and concatenates the results. f1
is alambda
that checks if the input is odd.f2
is alambda
that checks if the input is positive.surround
is alambda
which given a number, returns a string made by that number surrounded by square brackets.toStar
is alambda
which given any input returns the string'*'
.
This is my code:
def OR(f2, f1):
return lambda f1, f2 : True if (f1 or f2) else False
def AND(f1, f2):
return lambda f1, f2 : True if f1 and f2 else False
def CONCAT(f, g):
return lambda f, g : f + g
f1 = lambda f1: False if f1 % 2 == 0 else True
f2 = lambda f2: True if f2 > 0 else False
surround = lambda c : '[' + str(c) + ']'
toStar = lambda c : str(c) + '*'
a = 7
b = 9
c = 5
res1 = OR(f1, f2)(a)
res1b = AND(f1, f2)(a)
res2 = OR(f1, f2)(b)
res2b = AND(f1, f2)(b)
res3 = CONCAT(surround, toStar)(c)
res4 = CONCAT(toStar, surround)(c)
print()
Does anybody have a clue what I'm doing wrong?
Solution
OR
and AND
should return a function of one argument, which calls both of its wrapped functions on that argument:
def OR(f1, f2):
return lambda x: True if f1(x) or f2(x) else False
which can be simplified, if f1
and f2
are guaranteed to be predicates, to
def OR(f1, f2):
return lambda x: f1(x) or f2(x)
CONCAT
, similar, needs to call its wrapped functions:
def CONCAT(f1, f2):
return lambda x: f1(x) + f2(x)
(The caller of CONCAT
is responsible for ensuring that the return values of f1
and f2
are, in fact, valid operands to +
.)
Answered By - chepner
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.