Solved

Python Lambda functions

Posted on 2010-09-17
8
672 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 3

Accepted Solution

by:
1ce earned 300 total points
ID: 33705994

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 29

Assisted Solution

by:pepr
pepr earned 100 total points
ID: 33708957
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
ID: 33716172
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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 5

Expert Comment

by:-Richard-
ID: 33719839
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
 
LVL 29

Expert Comment

by:pepr
ID: 33722512
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 29

Expert Comment

by:pepr
ID: 33722526
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-
ID: 33725770
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
ID: 33740063
Thanks guys
0

Featured Post

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
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 …

624 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