473,503 Members | 8,959 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can this be written more concisely in a functional style

1)
def f(xs):
for x in xs:
if test(x): return True
return False

I know that I can do (2), but it operates on the whole list and the original
may break out early. I want the efficiency of (1), but the conciseness of (2).

2)
return True in map(test,xs)
Jul 18 '05 #1
16 1732
On 17 Nov 2003 16:48:36 -0800, MetalOne wrote:
1)
def f(xs):
for x in xs:
if test(x): return True
return False
Makes it obvious that there is a way for the iternation to end early.
2)
return True in map(test,xs)
Strongly implies ("foo in list", "map()") that the entire list will be
iterated. Any other behaviour would be unexpected to the person reading
the code.
I know that I can do (2), but it operates on the whole list and the
original may break out early. I want the efficiency of (1), but the
conciseness of (2).


I think that in seeking to make it more concise, you're also seeking to
make it less obvious. Anything that has the semantics of "loop over the
whole list" in a single statement, isn't going to help people understand
that a common case is for the iteration to end early. Which is probably
a good reason for it not to appear.

If you want to hide the algorithm, do so inside a helper function. Then
you have consision in the places where you're actually using it, and
explicit semantics where the algorithm is implemented.

--
\ "A cynic is a man who, when he smells flowers, looks around for |
`\ a coffin." -- Henry L. Mencken |
_o__) |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #2
On 18 Nov 2003 11:28:09 +1050, Ben Finney wrote:
On 17 Nov 2003 16:48:36 -0800, MetalOne wrote:
def f(xs):
for x in xs:
if test(x): return True
return False


If you want to hide the algorithm, do so inside a helper function.
Then you have consision in the places where you're actually using it,
and explicit semantics where the algorithm is implemented.


On second look, you appear to *be* putting this in a helper function,
presumably for the purpose of hiding the implementation. If so, it's a
good thing that the implementation is explicit here -- anyone who goes
looking into this function wants it obvious how it works.

--
\ "When I get real bored, I like to drive downtown and get a |
`\ great parking spot, then sit in my car and count how many |
_o__) people ask me if I'm leaving." -- Steven Wright |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #3
On 17 Nov 2003 16:48:36 -0800, jc*@iteris.com (MetalOne) wrote:
1)
def f(xs):
for x in xs:
if test(x): return True
return False

I know that I can do (2), but it operates on the whole list and the original
may break out early. I want the efficiency of (1), but the conciseness of (2).

2)
return True in map(test,xs)

That's not quite the same, unless you guarantee that test(x)==bool(test(x))==True when
test(x) is logically true, and never returns True otherwise. (E.g., what if test were
def test(x): return x ? f(range(5)) will give you a True when you hit 1 but, map(test,range(5))
will just be the numbers, and there will be no True in that).

I guess with generator expressions you will soon be able to write

def f(xs): return True in (bool(test(x)) for x in xs)

We can fake the generator expression and a test that will show us how far it went, to see...
def test(x): print x; return x=='3' ...
(Ok, that does guarantee a bool, but some other test might conceivably not).
def gx(fun, seq): ... for x in seq: yield bool(fun(x))
... xs = 'abc123def456'
and
def f(xs): return True in gx(test, xs) ... f(xs)

a
b
c
1
2
3
True

Regards,
Bengt Richter
Jul 18 '05 #4
Something like
return any( test, xs )
or
return xs.any( test )
?

--
Georgy Pruss
E^mail: 'ZDAwMTEyMHQwMzMwQGhvdG1haWwuY29t\n'.decode('base6 4')
"MetalOne" <jc*@iteris.com> wrote in message news:92**************************@posting.google.c om...
| 1)
| def f(xs):
| for x in xs:
| if test(x): return True
| return False
|
| I know that I can do (2), but it operates on the whole list and the original
| may break out early. I want the efficiency of (1), but the conciseness of (2).
|
| 2)
| return True in map(test,xs)
Jul 18 '05 #5
Maybe my post was not clear.
I want a means to test if there exists an element in the list that
satisfies a predicate.

Actually, when I word it that way, I guess what I want is PEP 289,
universal and existential qualifiers.

I guess I'll have to wait.
Jul 18 '05 #6
MetalOne wrote:
1)
def f(xs):
for x in xs:
if test(x): return True
return False

I know that I can do (2), but it operates on the whole list and the
original
may break out early. I want the efficiency of (1), but the conciseness of
(2).

2)
return True in map(test,xs)


[2] is quite different [1] in terms of semantics, of course. [1] will
accept any true (non-false) result, such as 23 or 'foo', [2] won't. If
[2]'s semantics are what you want,

return True in itertools.imap(test, xs)

should give you exactly what you require. Otherwise, you may want to
ensure a 'bool' is further applied, either by using a lambda or by
nesting two imap calls.
Alex

Jul 18 '05 #7
jc*@iteris.com (MetalOne) wrote in message news:<92**************************@posting.google. com>...
Maybe my post was not clear.
I want a means to test if there exists an element in the list that
satisfies a predicate.
Sure there is. The code that you showed was an excellent way to do
so.
Actually, when I word it that way, I guess what I want is PEP 289,
universal and existential qualifiers.

I guess I'll have to wait.


Why? Why not just stuff the code you wrote into an appropriately
named function and use that?

Anyway, here are more efficient implementations:

def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
else:
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
else:
return True

Jeremy
Jul 18 '05 #8
jc*@iteris.com (MetalOne) wrote in message news:<92c59a2c.0311171648.
return True in map(test,xs)


return True in itertools.imap(test,xs) ?

M.
Jul 18 '05 #9
tw*********@hotmail.com (Jeremy Fincher) wrote in message news:<69*************************@posting.google.c om>...
Anyway, here are more efficient implementations:

def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
else:
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
else:
return True

Jeremy


This is a perfect example of why I dislike the "else" clause. I
would code this as

def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
return True

Since the "else" is unnecessary, it disturbs me, I get confused,
I don't see why it is used (there is no break in the loop) and the
code becomes much harder to read, for me. OTOH I am sure 99% of
people would say "look, it is obvious, if elt is in the output
of ifilter it will return True, else False (viceversa in the
second case)". But may brain sees that the "else" is unncessary
and immediately it is disturbed by th redundance.
Am I the only one? ;)

Michele
Jul 18 '05 #10
Michele Simionato fed this fish to the penguins on Tuesday 18 November
2003 07:14 am:

This is a perfect example of why I dislike the "else" clause. I
would code this as
To one extant, for these examples in particular (due to the
shortness), I don't like either.

Think its my old "structured programming" indoctrination coming
through -- the "one way in, one way out" mentality.
def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
return True
I'd be wasting a local with

def any(p, seq):
"""ibid"""
a = False
for elt in itertools.ifilter(p, seq):
a = True
return a

and similar for the all()

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Bestiaria Home Page: http://www.beastie.dm.net/ <
Home Page: http://www.dm.net/~wulfraed/ <


Jul 18 '05 #11
Dennis Lee Bieber <wl*****@ix.netcom.com> writes:
def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
return True
I'd be wasting a local with

def any(p, seq):
"""ibid"""
a = False
for elt in itertools.ifilter(p, seq):
a = True

break return a


You're not just wasting a local.

'as
Jul 18 '05 #12
mi**@pitt.edu (Michele Simionato) writes:
Am I the only one? ;)


I think such code is likely to fool people into thinking that the else part of
loops is only executed if no single iteration takes place.

'as
Jul 18 '05 #13
tw*********@hotmail.com (Jeremy Fincher) writes:
jc*@iteris.com (MetalOne) wrote in message news:<92**************************@posting.google. com>...
Maybe my post was not clear.
I want a means to test if there exists an element in the list that
satisfies a predicate.


Sure there is. The code that you showed was an excellent way to do
so.
Actually, when I word it that way, I guess what I want is PEP 289,
universal and existential qualifiers.

I guess I'll have to wait.


Why? Why not just stuff the code you wrote into an appropriately
named function and use that?

Anyway, here are more efficient implementations:

def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
else:
return False


Another alternative (also works for python2.2, but is likely to be slower):

def some(predicate, *seqs):
iterables = map(iter, seqs)
try:
while 1:
boo = predicate(*[iterable.next() for iterable in iterables])
if boo: return boo
except StopIteration: return False

'as
Jul 18 '05 #14
mi**@pitt.edu (Michele Simionato) wrote:
def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
return True

Since the "else" is unnecessary, it disturbs me, I get confused,
I don't see why it is used (there is no break in the loop) and the
code becomes much harder to read, for me. OTOH I am sure 99% of
people would say "look, it is obvious, if elt is in the output
of ifilter it will return True, else False (viceversa in the
second case)". But may brain sees that the "else" is unncessary
and immediately it is disturbed by th redundance.
Am I the only one? ;)


Well, don't the multiple returns disturb you? I'd suggest this but
probably it's too clever:

from itertools import islice,ifilter

def any(predicate,seq):
return bool(list(islice(ifilter(predicate,seq),1)))

def test():
xs = 'abc123def456'
def fun(x):
print x
return x == '3'
print any(fun,xs)

if __name__=='__main__':
test()

Anton
Jul 18 '05 #15
My intention was that test() return True or False.
So True in itertools.imap(test, xs) is what I was looking for.

I also like the any() function suggested above.
def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
return False
In the itertools.imap version does
<True in> test against a continually growing list, ie.
True in [False]
True in [False, False]
True in [False, False, False]
True in [False, False, False, True]

or does it just apply <in> to the next generated element.

Is the itertools.imap version as efficient as the for loop version?
Thanks.
Jul 18 '05 #16
mi**@pitt.edu (Michele Simionato) wrote in message news:<22**************************@posting.google. com>...
tw*********@hotmail.com (Jeremy Fincher) wrote in message news:<69*************************@posting.google.c om>...
def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
else:
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
else:
return True
This is a perfect example of why I dislike the "else" clause. I
would code this as

def any(p, seq):
"""Returns true if any element in seq satisfies predicate p."""
for elt in itertools.ifilter(p, seq):
return True
return False

def all(p, seq):
"""Returns true if all elements in seq satisfy predicate p."""
for elt in itertools.ifilterfalse(p, seq):
return False
return True

Since the "else" is unnecessary, it disturbs me, I get confused,
I don't see why it is used (there is no break in the loop)


It's used because the for loop is effectively serving as an if
statement. Iterators have no __nonzero__ method -- you can't simply
bool() them. So I use a for loop like a if statement, and throw the
else in there to emphasize that usage. The for loop will never
iterate; either its body executes or it doesn't.

An alternative way to code this would be:

def any(p, seq):
try:
itertools.ifilter(p, seq).next()
return True
except StopIteration:
return False

but I find that less clear.

I also use else because it puts my return statements at the same level
of indentation, which I find more readable, since logically they're
equivalent.
Am I the only one? ;)


One can only hope! <wink>

Jeremy
Jul 18 '05 #17

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

Similar topics

30
3382
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...
1
2052
by: Paul THompson | last post by:
I am using IE to hide sections of a form. When I display the first section (name='ea'), the form widgets are not clickable in IE nor do they accept focus. When I display the 3rd section...
177
6854
by: C# Learner | last post by:
Why is C syntax so uneasy on the eye? In its day, was it _really_ designed by snobby programmers to scare away potential "n00bs"? If so, and after 50+ years of programming research, why are...
61
16166
by: /* frank */ | last post by:
I have to do a homework: make a CPU simulator using C language. I have a set of asm instructions so I have to write a program that should: - load .asm file - view .asm file - do a step by step...
38
3002
by: sopranos2 | last post by:
Dear IBM DB2 support, I wish CLP would have been more functional. Without living the command line I would like to get sql return code explanations, scalar function definitions etc.. Looking...
60
4867
by: Shawnk | last post by:
Some Sr. colleges and I have had an on going discussion relative to when and if C# will ever support 'true' multiple inheritance. Relevant to this, I wanted to query the C# community (the...
11
7016
by: dfeustel | last post by:
Even if there is no Java hardware, could not a Java OS be run by a Java interpreter? Or is there a fundamental problem? I've read that device drivers are hard to write in Java. Dave Feustel --...
1
1531
by: petermichaux | last post by:
Hi, I have a general JavaScript library API design question based on some examples I have seen. There seem to be two options The first option is used by the AJAX libraries and by Matt Kruse's...
11
1137
by: beginner | last post by:
Hi, If I have a number n and want to generate a list based on like the following: def f(n): l= while n>0: l.append(n%26) n /=26
15
1703
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...
0
7361
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7015
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...
0
7470
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...
0
5602
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,...
1
5026
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...
0
4693
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3183
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...
0
3173
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
403
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...

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.