473,320 Members | 1,865 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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

I was thinking about something like the following;
a=[ t**n for n in range(4) ] Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 't' is not defined
or
a=[ lambda t: t**n for n in range(4) ]
t=2
a [<function <lambda> at 0x403dcc6c>, <function <lambda> at 0x403dcca4>,
<function <lambda> at 0x403dccdc>, <function <lambda> at 0x403dcd14>] t=3
a [<function <lambda> at 0x403dcc6c>, <function <lambda> at 0x403dcca4>,
<function <lambda> at 0x403dccdc>, <function <lambda> at 0x403dcd14>]


is something like that possible? Will you give me advice about that?

Jul 19 '05 #1
17 1973
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 "<stdin>", line 1, in ?
NameError: name 't' is not defined
or

a=[ lambda t: t**n for n in range(4) ]
t=2
a
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
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 "<stdin>", line 1, in ?
NameError: name 't' is not defined
or

a=[ lambda t: t**n for n in range(4) ]
t=2
a
[<function <lambda> at 0x403dcc6c>, <function <lambda> at 0x403dcca4>,
<function <lambda> at 0x403dccdc>, <function <lambda> at 0x403dcd14>]
t=3
a


[<function <lambda> at 0x403dcc6c>, <function <lambda> at 0x403dcca4>,
<function <lambda> at 0x403dccdc>, <function <lambda> at 0x403dcd14>]
is something like that possible? Will you give me advice about that?

Jul 19 '05 #3
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
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 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
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 [<function unity at 0x401e609c>, <function identity at 0x401e6b54>,
<function square at 0x401e6b8c>, <function cube at 0x401e6ca4>]

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': <function <lambda> at 0x401e6bc4>, 't**1': <function <lambda> at 0x401e6bfc>,
't**2': <function <lambda> at 0x401e6c34>, 't**3': <function <lambda> 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
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

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
On 22 Apr 2005 14:41:45 -0700, me*************@gmail.com
<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 "<stdin>", line 1, in ?
NameError: name 't' is not defined
or
a=[ lambda t: t**n for n in range(4) ]
t=2
a [<function <lambda> at 0x403dcc6c>, <function <lambda> at 0x403dcca4>,
<function <lambda> at 0x403dccdc>, <function <lambda> at 0x403dcd14>] t=3
a [<function <lambda> at 0x403dcc6c>, <function <lambda> at 0x403dcca4>,
<function <lambda> at 0x403dccdc>, <function <lambda> 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
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 a
a=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 '<FunArray names: %s\n %r => %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 <FunArray names: x=0.0
'x' => [0.0, 1.0]> a.x [0.0, 1.0] a.y = 1.0
a.y [0.8414709848078965, 0.54030230586813977] a <FunArray names: x=0.0, y=1.0
'y' => [0.8414709848078965, 0.54030230586813977]> a.z = pi/3
a <FunArray names: x=0.0, y=1.0, z=1.0471975511965976
'z' => [0.8660254037844386, 0.50000000000000011]> a.x = pi/6
a

<FunArray names: y=1.0, z=1.0471975511965976, x=0.52359877559829882
'x' => [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
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
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
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
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
Mage <ma**@mage.hu> 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
Mage wrote:
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.


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
On 22 Apr 2005 20:45:55 -0700, "El Pitonero" <pi******@gmail.com> wrote:
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 morecards in your deck
before you try to play for real? ;-)


Communication problem.

Indeed.

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. This is essentially what I was demonstrating with the namespace of FunArray,
showing object attribute namespace access as perhaps _the_ 'listening" hook
of Python -- which properties and overriding base class methods with
subclass methods etc. etc. all depend on.

FunArray 'listens' for named "spreadsheet cell" assignments to its namespace,
and it "listens" for a repr access to the "spreadsheet" as a whole, presenting
its status in terms of cell names and the formula value of the last cell entered.

Not conventional, but I wanted to stay as close to the OP's proposed
example interactive log (if that was what it was, which apparently it wasn't ;-)

This does also demonstrate that if you want to "listen" for apparent
assignments to bare names, AFAIK there is no way without byte code hackery
or using a trace hook, or just doing your own eval-print loop,
which is why I suggested the cmd module as a start.

of course, you could mess with displayhook to get what the OP originally
appeared to be asking for. E.g., this toy produces an interactive log
much like the OP specified:
class DH(object): ... def __init__(self):
... import math
... self.env = vars(math)
... self.env.update(vars(__builtins__))
... def evalstrex(self, s):
... for name in compile(s,'','eval').co_names:
... if type(self.env[name]) == str:
... self.env[name] = self.evalstrex(self.env[name])
... return eval(s, self.env)
... def __call__(self, o):
... if type(o)==str:
... self.env.update(globals())
... o = self.evalstrex(o)
... sys.__displayhook__(o)
... import sys
sys.displayhook = DH()
Other than the quotes around the formula,
a = '[sin(x), cos(x)]'
x=0.0
a [0.0, 1.0] x=1.0
a [0.8414709848078965, 0.54030230586813977]

looks a lot like

"""
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.
"""

Of course, this is not what the OP _really_ wanted ;-)

But it's kind of fun. Anything you type in quotes is evaluated
using available global bindings plus the ones in the math module
and __builtins__, and it's recursive, so if a name in the quoted
formula refers to another string (which must be a valid expression),
that is evaluated, and so on. This is "pull" based on interactive
display trigger ;-)
x='pi/6'
a [0.49999999999999994, 0.86602540378443871]
x='pi/6'
a [0.49999999999999994, 0.86602540378443871] x = 'pi/y'
y=6
a [0.49999999999999994, 0.86602540378443871] y=3
a [0.8660254037844386, 0.50000000000000011]

The display hook passes through non-strings, so you can box a string formula to see it:
[a] ['[sin(x), cos(x)]'] [x] ['pi/y'] [y] [3]
You could specify your spread sheet:
a1,a2,a3=100,200,'sum([a1,a2])'
a1,a2,a3 (100, 200, 'sum([a1,a2])') a1 100 a2 200 a3

300

;-)

(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.


Regards,
Bengt Richter
Jul 19 '05 #17
On Saturday 23 April 2005 02:43 am, Mage wrote:
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.


Lambda has two main uses, IMHO:

1) You need to create a whole lot of functions which all follow a certain
pattern, but must evaluate "late" (i.e. the arguments will be added later,
so you can't just compute the result instead). This is basically the
case the OP presented with his list of increasing powers. You can, of
course, use named functions for each, but it may become impractical.

2) You are going to apply the same (arbitrary) function to many sets of arguments.
This argues for taking a function as an argument. Python Imaging Library
does this with the 'point' method, for example.

Frequently you will run into a trivial case such as:

def squared_plus_one(x):
return x**2 + 1

result_ob = source_ob(transform=squared_plus_one)

or something like that. It gets pretty silly to clutter up your code with such
trivial functions, and lambda gives you a neat way to simply define the function
for the moment you need it and throw it away:

result_ob = source_ob(transform=lambda x: x**2 + 1)

Note that in this case, the expression is probably the clearest way to document
the function (clearer than the function name, IMHO).

So, yeah, they have some real uses. But you can live without them most
of the time.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 19 '05 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Peter Barth | last post by:
Hi, trying to mix lambda expresions and list comprehension doesn't seem to work. --- >>> (2) 11 >>> (2) 11 --- I expected the second expression to return 6.
8
by: Ian McMeans | last post by:
I was bitten by a bug today that depended on how lambda works. It took me quite a while to realize what was going on. First, I made multiple lambda functions inside a loop, each of which...
9
by: Darabos Daniel | last post by:
Hi! I was doing something like this: >>> def p( x ): .... print x .... >>> l = >>> for i in range( 5 ): .... l.append( lambda: p( i ) )
1
by: Xin Wang | last post by:
Some c++ guru said c++ is hard to learn but easy to use. Is python easy for both aspect? I found lot's of confused in coding. #code from Tkinter import * def on_click(m): print m def...
4
by: markscottwright | last post by:
Just for the hell of it, I've been going through the old Scheme-based textbook "Structure and Interpretation of Computer Programs" and seeing what I can and can't do with python. I'm trying to...
181
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ...
5
by: Max Rybinsky | last post by:
Hello! Please take a look at the example. >>> a = # Just a list of tuples >>> a Now i want to get a list of functions x*y/n, for each (x, y) in a:
8
by: rubbishemail | last post by:
Hello, I need your help understanding lambda (and doing it a better way without). f = lambda x : x*x # this is a list of functions
4
by: wyleu | last post by:
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...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.