The Demise of lambda, map, filter and reduce


But, on the other hand:
(Toggle Plain Text) [i * i for i in l if i % 2 == 0] [i * i for i in l if i % 2 == 0]
Posted On: Tuesday 27th of November 2012 01:11:16 AM Total Views:  44
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




block/lambda

Playing with imitating lambdas and ruby blocks in Python, I came up with a very simple construct, for example: import compiler def dotimes(i, code): for i in range(i): exec code dotimes(5, ''' for j in range(i): print j, print ''', '', 'exec') This will print 0 0 1 0 1 2 0 1 2 3 A more efficient code would probably be dotimes(5, compiler.compile(''' for j in range(i): print j, print ''', '', 'exec')) which is, to my understanding, exactly what a ruby block is. But the actual "discovery" here, is that the triple quote - ''' - makes a syntax for block passing. Having a code editor that keeps colorizing what's inside the quotes like a normal code would make it easier to maintain. Is it possible to grant Python another syntactic mark, similar to triple quotes, that will actually make the enclosed code a compiled code, or an anonymous function I know that anonymous functions (long lambdas...) are not on the road map. But I ask this because, as I understand it, the triple quote actually presents a syntax for it. Isn't it actually a matter of taking the triple-quotes a little bit further
VIEWS ON THIS POST

31

Posted on:

Saturday 3rd November 2012
View Replies!

explain this function to me, lambda confusion

i have a rough understanding of lambda but so far only have found use for it once(in tkinter when passing lambda as an argument i could circumvent some tricky stuff). what is the point of the following function def addn(n): return lambda x,inc=n: x+inc if i do addn(5) it returns >>> def addn(n): return lambda x,inc=n: x+inc >>> addn(5) ok so what do i write to make it actually do something. and is the inc=n necessary i cant do x+n
VIEWS ON THIS POST

97

Posted on:

Sunday 4th November 2012
View Replies!

Weird lambda rebinding/reassignment without me doing it

I am never redefining the or reassigning the list when using validate but since it spits the modified list back out that somehow means that the modified list is part of the environment and not the old one. i thought what happend inside a function stays inside a function meaning what comes out is independent of what comes in. Meaning if I want the list I send as a parameter to the function I have to do x = func(x) and not just func(x) and x is magically what comes out of func(). Doesnt Python have closure or that isnt what this is about def validate(placed): student = round(random.random()*401) if student in placed: return validate(placed) else: placed.append(student) return student, placed def val(placed): student = round(random.random()*401) if student in placed: return validate(placed) else: placed.append(student) return student >>> g = lambda x:validate(x) >>> l=[] >>> for x in range(1,10): g(l) (141.0, [141.0]) (19.0, [141.0, 19.0]) (86.0, [141.0, 19.0, 86.0]) (120.0, [141.0, 19.0, 86.0, 120.0]) (76.0, [141.0, 19.0, 86.0, 120.0, 76.0]) (262.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0]) (234.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0]) (74.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0]) (325.0, [141.0, 19.0, 86.0, 120.0, 76.0, 262.0, 234.0, 74.0, 325.0]) >>> g = lambda x:val(x) >>> l=[] >>> for x in range(1,10): g(l) 183.0 33.0 315.0 244.0 308.0 168.0 146.0 378.0 297.0 >>>
VIEWS ON THIS POST

82

Posted on:

Sunday 4th November 2012
View Replies!

Re: dynimac code with lambda function creation

Justin Delegard wrote: > So I am trying to pass an object's method call to a function that > requires a function pointer. I figured an easy way to do it would be to > create a lambda function that calls the correct method, but this is > proving more difficult than I imagined. > > Here is the function I'm using: > > def objectMethodCallerFunctionCreator(testerObj, method): > exec("y=lambda x: testerObj."+method+"(x)") > return y > You are making it too difficult. What about this: def objectMethodCallerFunctionCreator(testerObj, method): return getattr(testerObj,method) BTW, when you need to return a value (instead of simple code execution) you should use eval() instead of exec(). > Where testerObj is an instance of an object, and method is a string > representing the method to call. The problem is, when I actually run > the function created (y in this case), it tells me it can't find the > symbol testerObj in the global scope. That is true. The 'testerObj' parameter is assigned to the local namespace. The local namespace is created when the function is called. When you call exec, it creates a new namespace. Thus, testerObj is not available inside exec(). But please see above - you do not need exec for this. It is unsafe, slow and really not necessary. > I am assuming this is happening because of the exec() call, but I don't > see another way of calling a variable method on an object. Generally, you should not use exec, eval and their counterparts to access certain attributes of different objects. Same for defining functions, classes, create instances etc. If you still feel that you need to use eval or exec for some reason, drop me an email and hopefully I can help avoiding it. :-) Best, Laszlo
VIEWS ON THIS POST

87

Posted on:

Sunday 4th November 2012
View Replies!

Re: block/lambda

On Tue, 29 Jul 2008 07:26:38 -0700 (PDT), "jiri.zahradil@gmail.com" wrote: > >> 2. Will it be possible in Python 3.0 to do the following: >> >> >>> def dotimes(n, callable): >> >> for i in range(n): callable() >> >> >>> def block(): >> >> nonlocal i >> for j in range(i): >> print j, >> print > >dotimes seems ok and what is wrong with that function "block" You do >not need to specify that i is "nonlocal", global i will be used. > >>>> i=10 >>>> def block(): > for j in range(i): > print j, > print >>>> block() >0 1 2 3 4 5 6 7 8 9 > Python doesn't have dynamic scoping. >>> def dotimes(n, callable): ... for i in range(n): ... callable() ... >>> def block(): ... for j in range(i): ... print j, ... print ... >>> def f(): ... dotimes(5, block) ... >>> f() Traceback (most recent call last): File "", line 1, in File "", line 2, in f File "", line 3, in dotimes File "", line 2, in block NameError: global name 'i' is not defined >>> The "nonlocal" keyword in Python 3 won't do this, either. It's for referencing names in outer lexical scopes, not outer dynamic scopes. Jean-Paul
VIEWS ON THIS POST

44

Posted on:

Sunday 4th November 2012
View Replies!

Question about lambda and variable bindings

I need to use a lambda expression to bind some extra contextual data (should be constant after it's computed) to a call to a function. I had originally thought I could use something like this demo (but useless) code: funcs=[] def testfunc(a,b): print "%d, %d" % (a,b) for x in xrange(10): funcs.append(lambda p: testfunc(x+2,p)) Now what I'd like is to call, for example, funcs[0](4) and it should print out "2,4". In other words I'd like the value of x+2 be encoded into the lambda somehow, for funcs[x]. However the disassembly shows this, which is reasonable, but not what I need: >>> dis.dis(funcs[0]) 2 0 LOAD_GLOBAL 0 (testfunc) 3 LOAD_GLOBAL 1 (x) 6 LOAD_CONST 0 (2) 9 BINARY_ADD 10 LOAD_FAST 0 (p) 13 CALL_FUNCTION 2 16 RETURN_VALUE The LOAD_GLOBAL 1 (x) line is definitely a problem. For one it refers to a variable that won't be in scope, should this lambda be called from some stack frame not descended from the one where I defined it. So how can I create a lambda expression that calculates a constant based on an expression, rather than referring to the object itself Can it be done Michael
VIEWS ON THIS POST

126

Posted on:

Sunday 4th November 2012
View Replies!

Re: Question about lambda and variable bindings

poof65 wrote: > An idea, i don't know if it will work in your case. > > for x in xrange(10): > funcs.append(lambda p,z=x: testfunc(z+2,p)) Good idea. I will try it. I also figured out a way to architecture my program differently to avoid this problem. But this idiom might be handy in certain situations. Suppose you need to provide a callback function with a fixed signature to some library routine. But you want to add extra contextual data to your callback. This just might be the ticket. Michael
VIEWS ON THIS POST

56

Posted on:

Monday 5th November 2012
View Replies!

Re: Question about lambda and variable bindings

"Michael Torrie" wrote in message news:47CA160C.3000305@gmail.com... |I need to use a lambda expression Lambda expressions are a convenience, not a necessity. When having a problem, it sometimes helps to revert to the unabbreviated def statement. tjr
VIEWS ON THIS POST

64

Posted on:

Monday 5th November 2012
View Replies!

Please explain collections.defaultdict(lambda: 1)

I'm reading http://norvig.com/spell-correct.html and do not understand the expression listed in the subject which is part of this function: def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model Per http://docs.python.org/lib/defaultdict-examples.html It seems that there is a default factory which initializes each key to 1. So by the end of train(), each member of the dictionary model will have value >= 1 But why wouldnt he set the value to zero and then increment it each time a "feature" (actually a word) is encountered It seems that each model value would be 1 more than it should be.
VIEWS ON THIS POST

82

Posted on:

Monday 5th November 2012
View Replies!

cute use of lambda

class FakeQueue(list): put = list.append get = lambda self: self.pop(0) ;]
VIEWS ON THIS POST

50

Posted on:

Monday 5th November 2012
View Replies!

lambda-funcs problem

, I need to create a Python list of lambda-funcs that are dependent on the number of the ones, for example F = [] for i in xrange(N): F.append(lambda x: x + i) however, the example don't work - since i in end is N-1 it yields x+ (N-1) for any func. So what's the best way to make it valid Evaluation speed is also very important to me. Thank you in advance, D.
VIEWS ON THIS POST

76

Posted on:

Monday 5th November 2012
View Replies!

Autogenerate functions (array of lambdas)

What I want to do is build an array of lambda functions, like so: a = [lambda: i for i in range(10)] (This is just a demonstrative dummy array. I don't need better ways to achieve the above functionality.) print [f() for f in a] results in: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9] rather than the hoped for: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Clearly, lambda is returning the object i, which is left at the last value of range(10). The following is my solution. t = lambda i: lambda: i a = [t(i) for i in range(10)] or the somewhat more terse: a = [(lambda i: lambda: i)(i) for i in range(10)] This gives the behavior which, intuitively, I expected from the original syntax. So my questions are: 1) Does this make sense as what should be done here That is, would this be the behavior you'd want more often than not As I said, intuitively, I would think the lambda would treat the iterator variable as a constant in this context. 2) Is there a better or preferred method than the one I've found
VIEWS ON THIS POST

130

Posted on:

Monday 5th November 2012
View Replies!

Re: Is this a bug of the lambda function

On Fri, 12 Oct 2007 01:00:47 -0400, Zhu Wayne wrote > > I have a short code which gives me strange results, the code is as follows: > > f = [lambda x: None]*5 > for j in range(0, 5): > f[j] = lambda x: float(j)*x > [...] > It seems only when I use the index j (which is declear with the lambda > function), I can get expected answer [...] 'j' is not declared with the lambda function. Inside the lambda, 'j' is a global name. Global names inside a function body are looked up when the function is called, not when the function is defined. You are actually defining five identical functions that look up the global name j, take its float value, and multiply that times the argument x. If the name 'j' is deleted, the functions won't run anymore. Observe: >>> f = [lambda x: None]*5 >>> for j in range(0, 5): .... f[j] = lambda x: float(j)*x .... >>> del j >>> f[0](1) Traceback (most recent call last): File "", line 1, in File "", line 2, in NameError: global name 'j' is not defined To get the behavior you expect, you're going to have to cause the name 'j' to be looked up (and frozen, so to speak) at the time the lambda is defined. One way to do that is to use a default function argument: >>> for j in range(0, 5): .... f[j] = lambda x, inner_j=j: float(inner_j)*x .... >>> del j >>> f[0](1.) 0.0 Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net
VIEWS ON THIS POST

71

Posted on:

Monday 5th November 2012
View Replies!

return reduce(lambda x, y: x.grade+y.grade, self.reviews)

class Customer(object): def __init__(self, idnumber, review): self.idnumber = idnumber self.reviews = [review] def addReview(self, review): self.reviews.append(review) def averageGrade(self): tot = 0 for review in self.reviews: tot += review.grade return tot / len(self.reviews) def av_grade(self): return reduce(lambda x, y: x.grade+y.grade, self.reviews) now,the function is pointless and incorrect but av_grade doesn't work. why can't i use reduce like this
VIEWS ON THIS POST

126

Posted on:

Wednesday 7th November 2012
View Replies!

parameters to lambda's executed at run time.

I'm trying to supply parameters to a function that is called at a later time as in the code below: llist = [] for item in range(5): llist.append(lambda: func(item)) def func(item): print item for thing in llist: thing() which produces the result IDLE 1.2.1 >>> ================================ RESTART ================================ >>> >>> ================================ RESTART ================================ >>> 4 4 4 4 4 >>> How can one allocate a different parameter to each instance of the function rather than all of them getting the final value of the loop
VIEWS ON THIS POST

68

Posted on:

Wednesday 7th November 2012
View Replies!

dynimac code with lambda function creation

So I am trying to pass an object's method call to a function that requires a function pointer. I figured an easy way to do it would be to create a lambda function that calls the correct method, but this is proving more difficult than I imagined. Here is the function I'm using: def objectMethodCallerFunctionCreator(testerObj, method): exec("y=lambda x: testerObj."+method+"(x)") return y Where testerObj is an instance of an object, and method is a string representing the method to call. The problem is, when I actually run the function created (y in this case), it tells me it can't find the symbol testerObj in the global scope. I have successfully created similar functions, except without using the exec() call. e.g. def functionCreator(a, b, c): return lambda d: myFunc(a, b, c, d) and it doesn't complain about the variables a, b, or c when being run. I am assuming this is happening because of the exec() call, but I don't see another way of calling a variable method on an object. Is there some other way to do this that I'm missing I tried passing in 'method' as a function pointer (to the method of the object), but that didn't work either.
VIEWS ON THIS POST

82

Posted on:

Wednesday 7th November 2012
View Replies!

Not entirely serious: recursive lambda?

I came across the "japh" concept today and decided to do one of my own, obviously, interpreting the 'p' somewhat loosely, http://en.wikipedia.org/wiki/JAPH but I'm not entirely satisfied with it: #### # japh, for certain values of 'p' f=lambda(r,N):N and f((" ...
VIEWS ON THIS POST

113

Posted on:

Sunday 11th November 2012
View Replies!

iter(lambda:f.read(8192),'')

what is the difference between iter(lambda:f.read(8192), ') and iter(f.read(8192),'') ...
VIEWS ON THIS POST

67

Posted on:

Sunday 11th November 2012
View Replies!

object-relational mappers

I've been poking around the world of object-relational mappers and it inspired me to coin a corellary to the the famous quote on regular expressions: "You have objects and a database: that's 2 problems. So: get an object-relational mapper: now ...
VIEWS ON THIS POST

92

Posted on:

Sunday 25th November 2012
View Replies!

Bitmap editor and File-saving

In my Python program (using Tkinter), I would like to have a window where the user will be able to draw a simple picture. I don't know where to begin.. can somehow give me a general idea how to do ...
VIEWS ON THIS POST

51

Posted on:

Monday 26th November 2012
View Replies!