455,587 Members | 1,575 Online
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

# a=[ lambda t: t**n for n in range(4) ]

 P: n/a I was thinking about something like the following; a=[ t**n for n in range(4) ] Traceback (most recent call last): File "", line 1, in ? NameError: name 't' is not defined or a=[ lambda t: t**n for n in range(4) ] t=2 a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] t=3 a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] is something like that possible? Will you give me advice about that? Jul 19 '05 #1
17 Replies

 P: n/a me*************@gmail.com wrote: I was thinking about something like the following;a=[ t**n for n in range(4) ] Traceback (most recent call last): File "", line 1, in ? NameError: name 't' is not defined ora=[ lambda t: t**n for n in range(4) ]t=2a Perhaps you mean: a = lambda t: [t**n for n in range(4)] a(2) [1, 2, 4, 8] but that is better written as: def a(t): ... return [t**n for n in range(4)] ... a(2) [1, 2, 4, 8] Michael Jul 19 '05 #2

 P: n/a Please post a description of what you are trying to accomplish instead of asking us to take your possible solution and try to figure out what the problem was. You can do: def foo(t, r): return [t**n for n in range(r)] a=foo(2, 4) a [1, 2, 4, 8] a=foo(3,6) a [1, 3, 9, 27, 81, 243] but I don't really know what you want. Larry me*************@gmail.com wrote: I was thinking about something like the following;a=[ t**n for n in range(4) ] Traceback (most recent call last): File "", line 1, in ? NameError: name 't' is not defined ora=[ lambda t: t**n for n in range(4) ]t=2a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>]t=3a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] is something like that possible? Will you give me advice about that? Jul 19 '05 #3

 P: n/a Thanx for your replies. I'm looking for array of functions. Something like a=[ sin(x) , cos(x) ] x=0.0 a [0, 1] x=1.0 a .... of course it can be made by def cratearray(x): .... ~~~~ .... return a a=createarray(1.0) but this isn't what i am asking for. something automized. Jul 19 '05 #4

 P: n/a me*************@gmail.com wrote: Thanx for your replies. I'm looking for array of functions. Something like a=[ sin(x) , cos(x) ]x=0.0a [0, 1]x=1.0a ... of course it can be made bydef cratearray(x): ... ~~~~ ... return a a=createarray(1.0) but this isn't what i am asking for. something automized. Still, guessing, but perhaps this: def make_func_map(*funcs): ... def f(x): ... return [func(x) for func in funcs] ... return f ... from math import sin, cos, pi a = make_func_map(sin, cos) a(0) [0.0, 1.0] a(pi) [1.2246063538223773e-016, -1.0] Michael Jul 19 '05 #5

 P: n/a On Friday 22 April 2005 05:18 pm, me*************@gmail.com wrote: Thanx for your replies. I'm looking for array of functions. Something like a=[ sin(x) , cos(x) ] You had a list of lambda functions in your first post and in the subject line still. How is that not what you wanted? If you want an *answer*, you need to ask a *question*. Perhaps you don't know how to call such functions? E.g.: a=[ lambda t: t**n for n in range(4) ] a[2](3) 27 If you want to see *names* for the functions, you have two choices: either used named functions, def unity(t): return 1 def identity(t): return t def square(t): return t**2 def cube(t): return t**3 a = [unity, identity, square, cube] a [, , , ] or replace the list with a dictionary, e.g.: a = dict([('t**%d' % n, lambda t: t**n) for n in range(4)]) a {'t**0': at 0x401e6bc4>, 't**1': at 0x401e6bfc>, 't**2': at 0x401e6c34>, 't**3': at 0x401e6c6c>} a.keys() ['t**0', 't**1', 't**2', 't**3'] a['t**3'](4) 64 -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com Jul 19 '05 #6

 P: n/a Terry Hancock wrote: On Friday 22 April 2005 05:18 pm, me*************@gmail.com wrote: Perhaps you don't know how to call such functions? E.g.: a=[ lambda t: t**n for n in range(4) ]a[2](3) 27 Didn't you notice this was a funny value? Maybe this example will show you what is going wrong: a[0](3) 27 n = 10 a[3](2) 1024 See, the body of your anonymous function just looks for "the current value of n" when it is _invoked_, not when it is _defined_. Perhaps you mean: a = [lambda t, n=n: t**n for n in range(4)] which captures the value of n as a default parameter at definition time. In that case you get: a = [lambda t, n=n: t**n for n in range(4)] a[0](1024) 1 a[1](512) 512 a[2](16) 256 a[3](4) 64 --Scott David Daniels Sc***********@Acm.Org Jul 19 '05 #7

 P: n/a Thanx. It just popped in my mind. in 3d programming there are transformation matrices like a=[[cos(x),sin(x),0],[-sin(x),cos(x),0],[0,0,1]] it is a 3x3 matrix. never changes during program. it can be defined like def transmat(x): .... dummy=[[0,0,0],[0,0,0],[0,0,0]] .... dummy[0][0]=cos(x) .... ~~~~~~ .... return dummy a=transmat(1.0) it is usual way for this. i wonder if there is an automatic way to make that without calling a function. an automatic way that depends on changing the value of x. as each time x=something used the whole matrix changes automaticly. or maybe i am just dreaming. :) Jul 19 '05 #8

 P: n/a On 22 Apr 2005 14:41:45 -0700, me*************@gmail.com wrote: I was thinking about something like the following; a=[ t**n for n in range(4) ] Traceback (most recent call last): File "", line 1, in ? NameError: name 't' is not defined or a=[ lambda t: t**n for n in range(4) ] t=2 a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] t=3 a [ at 0x403dcc6c>, at 0x403dcca4>, at 0x403dccdc>, at 0x403dcd14>] Well, everybody else took away your lambda (greedy people!) but I'm here to say that it doesn't *have* to go away. I didn't think this would be possible, but it is: t = 2 [(lambda n: t**n)(n) for n in range(4)] [1, 2, 4, 8] t = 3 [(lambda n: t**n)(n) for n in range(4)] [1, 3, 9, 27] I just thought that was kinda neat. If you wanted to obfuscate some python, this would be an awesome trick - hide the value of t somewhere early in the function then pull a variation of this out later. Peace Bill Mill bill.mill at gmail.com Jul 19 '05 #9

 P: n/a On 22 Apr 2005 15:18:53 -0700, me*************@gmail.com wrote: Thanx for your replies.I'm looking for array of functions.Something like a=[ sin(x) , cos(x) ] x=0.0 a[0, 1] x=1.0 a...of course it can be made by def cratearray(x):... ~~~~... return aa=createarray(1.0)but this isn't what i am asking for. something automized. I still don't know what you are asking for, but here is a toy, whose code you will be able to improve on later, but at least provides concrete behavior that you can comment on, and maybe explain what you are really asking for. class FunArray(object): ... def __init__(self, *funs): ... self.__dict__['_funs'] = funs ... self.__dict__['_names'] = [] ... vars ... def __getattribute__(self, attr): ... if attr.startswith('_') or hasattr(type(self), attr): ... return object.__getattribute__(self, attr) ... v = vars(self).get(attr) ... if v is None: return ['%r is not set'%attr] ... return [f(v) for f in self._funs] ... def __setattr__(self, attr, v): ... if attr.startswith('_'): raise AttributeError, attr ... else: ... if attr in self._names: self._names.remove(attr) ... self._names.append(attr) ... self.__dict__[attr] = v ... def __repr__(self): ... last = self._names and self._names[-1] or '??' ... d= vars(self) ... return ' %s>'% ( ... ', '.join(['%s=%r'%(k, d[k]) for k in self._names]), ... last, repr(getattr(self, last))) ... from math import sin, cos, pi a = FunArray(sin, cos) a.x = 0.0 a [0.0, 1.0]> a.x [0.0, 1.0] a.y = 1.0 a.y [0.8414709848078965, 0.54030230586813977] a [0.8414709848078965, 0.54030230586813977]> a.z = pi/3 a [0.8660254037844386, 0.50000000000000011]> a.x = pi/6 a [0.49999999999999994, 0.86602540378443871] If you just want an interactive calculator that acts according to your taste, you can program one to prompt and read (use raw_input, not input BTW) what you type in and calculate and print whatever form of result you'd like. See the cmd module for one way not to reinvent some wheels. But why not spend some time with the tutorials, so have a few more cards in your deck before you try to play for real? ;-) Regards, Bengt Richter Jul 19 '05 #10

 P: n/a Bengt Richter wrote: I still don't know what you are asking for, but here is a toy, ... But why not spend some time with the tutorials, so have a few more cards in your deck before you try to play for real? ;-) Communication problem. All he wanted is automatic evaluation a la spreadsheet application. Just like in Microsoft Excel. That's all. There are many ways for implementing the requested feature. Here are two: (1) Push model: use event listeners. Register dependent quantities as event listeners of independent quantities. When an independent quantity is modified, fire off the event and update the dependent quantities. Excel uses the push model. (2) Pull model: lazy evaluation. Have some flag on whether an independent quantity has been changed. When evaluating a dependent quantity, survey its independent quantities recursively, and update the cached copies whereever necessary. Of course, combination of the two approaches is possible. For Python, metaclasses and/or decorators and/or properties may help. But functional languages are a more natural territory. Jul 19 '05 #11

 P: n/a On Friday 22 April 2005 06:44 pm, Scott David Daniels wrote: Terry Hancock wrote: On Friday 22 April 2005 05:18 pm, me*************@gmail.com wrote: Perhaps you don't know how to call such functions? E.g.: a=[ lambda t: t**n for n in range(4) ]>a[2](3) 27 Didn't you notice this was a funny value? Nope. Wasn't paying attention. ;-) Just copied the code from the OP. Perhaps you mean: a = [lambda t, n=n: t**n for n in range(4)] This is of course what he should've written, and/or what I should've corrected it to, thank you. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com Jul 19 '05 #12

 P: n/a Scott David Daniels wrote: See, the body of your anonymous function just looks for "the current value of n" when it is _invoked_, not when it is _defined_. The "lambda functions" was an unclear part of the tutorial I read. Should I use them? Are they pythonic? As far I see they are good only for type less a bit. Mage Jul 19 '05 #13

 P: n/a me*************@gmail.com wrote: i wonder if there is an automatic way to make that without calling a function. You mean without _explicitely_ calling a function. May I inquire why you need to write f instead of f(x)? an automatic way that depends on changing the value of x. as each time x=something used the whole matrix changes automaticly. As pointed out by El Pitonero property can be your friend: class A(object): ... def get_v(self): ... return [1,x] ... v=property(get_v) ... a=A() x=0 a.v [1, 0] x=2 a.v [1, 2] However, you will calculate your matrix each time you will access it (and I find it ugly to use a global variable this way). You can however build it the other way round: class B(object): ... def __init__(self): ... self.v=[1,0] ... self.x=0 ... def calc_v(self): ... self.v[1]=self.__x ... def set_x(self,x): ... self.__x=x ... self.calc_v() ... def get_x(self): ... return self.__x ... x=property(get_x, set_x) ... b=B() b.v [1, 0] b.x=2 b.v [1, 2] This time, calculations only occur when you change the value of x. Jul 19 '05 #14

 P: n/a Mage wrote in news:mailman.2339.1114242211.1799.python- The "lambda functions" was an unclear part of the tutorial I read. Should I use them? Are they pythonic? As far I see they are good only for type less a bit. And to obfusicate code. lambda is evil, do not play with it. Harald Jul 19 '05 #15

 P: n/a Mage wrote: Scott David Daniels wrote:See, the body of your anonymous function just looks for "the currentvalue of n" when it is _invoked_, not when it is _defined_. The "lambda functions" was an unclear part of the tutorial I read. Should I use them? Are they pythonic? As far I see they are good only for type less a bit. As for most python features which are not "dead obvious", you should only use them where they they make the code clearer than it would be without the use of that feature. In this case, I was responding to a particular use of lambda which, in fact, had a flaw that made the code do something different from what it looked like it was doing. I felt the distinction was clearer in the lambda form than it would have been with "def-style" function definitions. One of the reasons the distinction came out was that there was no confusing naming of "what this function means," only program structure. In a real program that is a hindrance. In the case of pointing out a flaw, it makes differences between two versions of some code more obvious. --Scott David Daniels Sc***********@Acm.Org Jul 19 '05 #16