Solved

Python Lambda functions

Posted on 2010-09-17
8
658 Views
Last Modified: 2012-08-14
I have a question regarding lambda functions in python. I made this general because this involves a homework assignment.

I call a function, lets say:

command prompt (ipython)>>>a = [1,2,3]
command prompt (ipython)>>>b = [1,2,3]
command prompt (ipython)>>> thingy(lambda a: a == b)

def thingy(hello):
    (if hello is true):
         return []
   return "EPIC FAIL"

So here's the question... I HAVE NO IDEA how to test if HELLO IS TRUE within the function.

Python is new to me and I don't know much about booleans. Right now I have in place of "(if hello is true)" -- "if hello is True:"

This is not working correctly!! It doesn't return correctly. Any help would be great!
0
Comment
Question by:jeffiepoo
8 Comments
 
LVL 3

Accepted Solution

by:
1ce earned 300 total points
Comment Utility

def thingy(hello):
    if hello:
        return ""
    return "EPIC FAIL"
compare = lambda x,y: x == y

a = [1,2,3]
b = [1,5,3]

for i in [0,1,2]:
    print str(i) + thingy(compare(a[i],b[i]))
0
 
LVL 28

Assisted Solution

by:pepr
pepr earned 100 total points
Comment Utility
Generally, if v is a boolean variable, then

    if v is True:

or

    if v == True:

or the like is a kind of not nice or confusing way of testing.  The "if" expects the boolean condition (the boolean result of an expression).  Put the constant values instead of v and you can see:

    if True is True:
...
    if False is True:
...
    if True == True:
...
    if False == True:

Or you can go to the verbal extreme:

    if (v does not hold) does hold:                  # this is not abou the syntax which is not acceptable by Python


1ce shows the way how it should be done.  In my opinion, the key point to fix the code also is to replace the "hello" identifier to something more meaningfull.
0
 
LVL 5

Assisted Solution

by:-Richard-
-Richard- earned 100 total points
Comment Utility
I"ll throw in my two-cents worth too.  .  

I think you are not real clear on what lambda functions really are.  They are "anonymous" functions which the "lambda" keyword allows you to define without ever giving it a name.  The anonymous function thusly defined will always accept as a parameter the variable (or comma-separated list of variables) on the left of the colon, and will always return as a value the expression on the right side of the colon.  Thus you can think of this expression:

        myfunc = lambda x: x == 2
       
as being equivalent to        

        def anonymous(x):
                return x == 2
               
        myfunc = anonymous
       
This creates a function named "myfunc" that accepts one parameter and tests if that parameter is 2.  Note that no function called "anonymous" is ever actually created - but you can think of what's happening as if it was.

At this point, if you want to evaluate this function, you would do so by calling myfunc and passing it a parameter:

        x = 1
        if (myfunc(x)):
                print "X is 2"
        else
                print "X is not 2"

(prints "X is not 2")

So in your original example, your lambda expression defines a function that takes one parameter.  As a result, strictly speaking, the direct answer to your original question, "how do I test if hello is true within the function", is this:  you must pass hello a single parameter for it to evaluate.  Thus in your original sample code, strictly speaking you would need to change it to:

        def thingy(hello):
                if hello('SOME PARAMETER GOES HERE'):
                        return []
                return "EPIC FAIL"
               
However, "thingy's" problems go deeper that that, because as defined, you don't have any parameter to pass to hello inside thingy.  This is what led to 1ce's solution where he defines a lambda with 2 parameters; then he actually evaluates that lambda prior to calling thingy, which in his version does nothing but test the result, circumventing the issue of what parameters to pass to "hello" from inside "thingy".
0
 
LVL 5

Expert Comment

by:-Richard-
Comment Utility
I'll add one further note - you say that currently thingy is written as "if hello is True:".  This will not work because, since you are failing to supply a parameter to hello, the Python interpreter understands the "hello" as referring to the function object itself, rather than a call to it.  That statement would therefore test whether the function reference passed in is identical to the value True, which it never is, so that statement would simply fail the test every time.  
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 28

Expert Comment

by:pepr
Comment Utility
Richard is completely right.  If the hello was used without anything (i.e. "if hello: ..."), then the function object would be evaluated as expression in the boolean context as True -- see the doc 5.10. Boolean operations http://docs.python.org/reference/expressions.html#boolean-operations which says:

"In the context of Boolean operations, and also when expressions are used by  control flow statements, the following values are interpreted as false: False, None, numeric zero of  all types, and empty strings and containers (including strings, tuples, lists,  dictionaries, sets and frozensets). All other values are interpreted as true.  (See the __nonzero__() special method for a way to change  this.)"

In your original question, you should not put parentheses around the if command.  The parentheses are not neccessary even around the boolean condition (unlike in C-family languages).  The constants for the boolean type are True and False with capital letters.  As Richard said, after correcting that (as he has shown) you will always get the  "EPIC FAIL".  Try the following interactive example:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a == b
True
>>> (lambda a: a == b)
<function <lambda> at 0x000000000203D828>
>>> bool(lambda a: a == b)
True
>>> b = []
>>> bool(lambda a: a == b)
True

The bool() function returns the boolean value of whatever object is passed in.  It returns the same value that would be evaluated in a boolean context.  As the doc (above says), the function object does not fall into category of things evaluated as False.  It is always evaluated as True.  However, the operator "is" does not introduce a boolean context.  It compares the object that represents the lambda function with the object that represents the constant True.

This way, 1ce changed the testing to use the boolean context evaluation (always True), Richard shown that using "hello is True" will evaluate always to False for the lambda function.
0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
If in doubt, leave the lambda out.  It is sometimes easier to understand the things without lambda calculus functions (at least for beginners).
0
 
LVL 5

Expert Comment

by:-Richard-
Comment Utility
So just to wrap it up in a neat package, here's is a way to implement your sample program which evaluates your lambda function to compare a and b from within thingy, obtaining parameters to pass it from the user.   I'm using your naming conventions so you can see more easily the relation of this program to the original, but as my esteemed colleague Pepr has pointed out, you really should come up with more descriptive names.  

def thingy( hello):
    left = input("Enter left side of comparison: ")
    right = input("Enter right side of comparison: ")
    if hello( left, right):
        print "They are equal."
    else:
        print "They are not equal"

>>> thingy( lambda a,b: a == b)
Enter left side of comparison: [1,2,3]
Enter right side of comparison: [1,2,3]
They are equal
>>> thingy( lambda a,b: a==b)
Enter left side of comparison: "hello"
Enter right side of comparison: "world"
They are not equal

Some notes:  

The "input" statement expects a Java object, so strings must be entered with quotes around them, otherwise you'll get an exception.  For clarity I didn't put exception handling in.

Also note that in the lambda expression, there is no need for the program to define "a" and "b" prior to running thingy, as you had attempted to do in your original sample.  Those are purely syntactical placeholders used in the definition of the anonymous function.  
0
 
LVL 6

Author Closing Comment

by:jeffiepoo
Comment Utility
Thanks guys
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

A set of related code is known to be a Module, it helps us to organize our code logically which is much easier for us to understand and use it. Module is an object with arbitrarily named attributes which can be used in binding and referencing. …
Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now