473,657 Members | 2,572 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Making things more functional in Python

Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors

Namely, I'd like to get rid of the initilization
(vectors = {}) and also the loop Yet, I'd hate to put
an assignment into Python's FP list comprehensions.

Ideally, I'd like something like this:
vectors.dict_ad d({d:result}) for [sample.get_val( d)
for sample in samples for d in dset].

Is there anything like that? Am I missing the
picture?

Thanks.

PS If possible, please cc me on all responses, thanks.


_______________ _______________ ____
Celebrate Yahoo!'s 10th Birthday!
Yahoo! Netrospective: 100 Moments of the Web
http://birthday.yahoo.com/netrospective/
Jul 18 '05 #1
6 1255
gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors

Namely, I'd like to get rid of the initilization
(vectors = {}) and also the loop
Generate the whole dictionary on the fly with a Python 2.4 generator
expression:

dict((d, [sample.get_val( d) for sample in samples]) for d in dset)

Whether this is "better" or not I think mainly hinges on which
one you ahve an easier time understanding later. Personally I would
prefer this version, but it's easy to get carried away trying to
functionalize things to the point that a procedural version is much
easier to understand.
Yet, I'd hate to put an assignment into Python's FP list
comprehensions.
Indeed it's not possible to have an assignment in a list comprehension.
(Unless it's a side-effect due to a function called by the list
comprehension.)
Ideally, I'd like something like this:
vectors.dict_ad d({d:result}) for [sample.get_val( d)
for sample in samples for d in dset].


You can't use the name "vectors" without first initializing it
somehow!
--
Michael Hoffman
Jul 18 '05 #2
gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors

Namely, I'd like to get rid of the initilization
(vectors = {}) and also the loop Yet, I'd hate to put
an assignment into Python's FP list comprehensions.

Ideally, I'd like something like this:
vectors.dict_ad d({d:result}) for [sample.get_val( d)
for sample in samples for d in dset].

Is there anything like that? Am I missing the
picture?

Thanks.

PS If possible, please cc me on all responses, thanks.

The logical thing to use would be

return dict([(d, sample.getval(d )) for d in dset for sample in samples])

which (I think) should work from 2.2 onwards.

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #3
Steve Holden wrote:
return dict([(d, sample.getval(d )) for d in dset for sample in samples])


That won't do what the original code does. This sets dict[d] to
samples[-1].getval(d) instead of [sample.getval(d ) for sample in samples].
--
Michael Hoffman
Jul 18 '05 #4
Michael Hoffman wrote:
Steve Holden wrote:
return dict([(d, sample.getval(d )) for d in dset for sample in samples])

That won't do what the original code does. This sets dict[d] to
samples[-1].getval(d) instead of [sample.getval(d ) for sample in samples].


My bad, I didn;t look closely enbough to see the need for the nested
comprehensions.

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.pycon.org/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #5
On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors


You could use reduce:

def compute_vectors (samples, dset):
def add_entry(vecto rs, d):
vectors[d] = [sample.get_val( d) for sample in samples]
return vectors
return reduce(add_entr y, dset, {})

Dave
Jul 18 '05 #6
On Sat, 2005-03-05 at 00:00 -0700, Dave Benjamin wrote:
On Fri, 2005-03-04 at 08:36 -0800, gf gf wrote:
Is there a better, more FP style, more Pythonic way to
write this:

def compute_vectors (samples, dset):
vectors = {}
for d in dset:
vectors[d] = [sample.get_val( d) for sample in
samples]
return vectors


You could use reduce:

def compute_vectors (samples, dset):
def add_entry(vecto rs, d):
vectors[d] = [sample.get_val( d) for sample in samples]
return vectors
return reduce(add_entr y, dset, {})


This could be further generalized:

def compute(xs, ys, f):
def add_entry(resul t, y):
result[y] = [f(x, y) for x in xs]
return result
return reduce(add_entr y, ys, {})

Now, compute_vectors is just:

compute(samples , dset, lambda x, y: x.get_val(y))

You could even abstract the method call:

def method(name):
def _method(obj, *args, **kwds):
return getattr(obj, name)(*args, **kwds)
return _method

compute(samples , dset, method('get_val '))

Dave
Jul 18 '05 #7

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

Similar topics

30
3436
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
12
1663
by: Ryan Paul | last post by:
I've spent a lot of time using python, and personally, I feel like it is vastly superior when compared to languages like java, and c++, but there are still a few things that detract from its elegance and flexibility. I thought I might mention a few of them. I'd like to hear what people think of my complaints, and I also like to hear the complaints of others. 1. many keywords (eg:try/except) are strictly imperative, and cannot be used in...
8
1562
by: beza1e1 | last post by:
I see myself shifting more and more over to the functional kind of coding. Could be related to the Haskell, we had to learn in CS. Now i was wondering, how other people use Python? With functional i mean my files mostly consist of functions and only rarely i use "class". The library modules seem to be mostly written the object-way on the other hand. If you use both paradigms. What are your criterias to choose the right method for a...
0
2257
by: Xah Lee | last post by:
One-Liner Loop in Functional Style Xah Lee, 200510 Today we show a example of a loop done as a one-liner of Functional Programing style. Suppose you have a list of file full paths of images: /Users/t/t4/oh/DSCN2059m-s.jpg
17
1977
by: ToddLMorgan | last post by:
I'm just starting out with python, after having a long history with Java. I was wondering if there were any resources or tips from anyone out there in Python-land that can help me make the transition as successfully as possible? Perhaps you've made the transition yourself or just have experience with folks who have made the transition. I'm looking for the common types of mistakes that say a Java/C# or even C++ developer may commonly...
15
1723
by: Lorenzo Stella | last post by:
Hi all, I haven't experienced functional programming very much, but now I'm trying to learn Haskell and I've learned that: 1) in functional programming LISTS are fundmental; 2) any "cycle" in FP become recursion. I also know that Python got some useful tool such as map, filter, reduce... so I told: "let's try some FP-style programming with Python!". I took a little example of Haskell: listprimes :: Integer -
16
2394
by: Andrea Gavana | last post by:
Hi Diez & All, Do you mind explaining "why" you find it *buttugly*? I am asking just out of curiosity, obviously. I am so biased towards wxPython that I won't make any comment on this thread in particular, but I am curious to know why some people find it "ugly" or "bad" or whatever. It has its own bugs and missing features, of course, but it is one of the major GUI player in the arena, together with PyQt and PyGTK.
10
984
by: James Fassett | last post by:
Hi all, Had a simple problem that turned into an interesting solution and I thought I would share it here. I had a list of tuples that I needed to get the first value from and generate a list. tuple_list = ( ('John', 'Doe'),
50
4471
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): //------------------------------------------------------------------ template<typename Data_t> class SmartPointer { Data_t* data; void(*deleterFunc)(Data_t*);
0
8425
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
8845
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
8522
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
8622
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7355
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
6177
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
4173
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...
1
2745
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
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.