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

Bengt Richter bokr at oz.net
Fri Apr 22 21:42:35 EDT 2005


On 22 Apr 2005 15:18:53 -0700, mehmetmutigozel at 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



More information about the Python-list mailing list