473,796 Members | 2,867 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2005
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(s in, cos)
a(0) [0.0, 1.0] a(pi) [1.2246063538223 773e-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 anansispacework s.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***********@A cm.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(se lf), attr):
... return object.__getatt ribute__(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__(sel f, attr, v):
... if attr.startswith ('_'): raise AttributeError, attr
... else:
... if attr in self._names: self._names.rem ove(attr)
... self._names.app end(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(se lf, 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.8414709848078 965, 0.5403023058681 3977] a <FunArray names: x=0.0, y=1.0
'y' => [0.8414709848078 965, 0.5403023058681 3977]> a.z = pi/3
a <FunArray names: x=0.0, y=1.0, z=1.04719755119 65976
'z' => [0.8660254037844 386, 0.5000000000000 0011]> a.x = pi/6
a

<FunArray names: y=1.0, z=1.04719755119 65976, x=0.52359877559 829882
'x' => [0.4999999999999 9994, 0.8660254037844 3871]
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

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

Similar topics

4
3040
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
2630
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 depended on the current loop variable. >>> a = >>> for index in range(5): a.append(lambda: index)
9
1636
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
374
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 lamb_on_click(m):
4
1634
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 create a function that returns the function (not the results of the function, but a function object) that results from applying function f to it's (single) argument N times. For example, if you have "def sq(x): return x*x", then repeated(sq, 2)(2)...
181
8918
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 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him.
5
2523
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
339
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
1007
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 item
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9525
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10452
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10169
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9050
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7546
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5440
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.