473,847 Members | 1,853 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reduce() anomaly?

This seems like it ought to work, according to the
description of reduce(), but it doesn't. Is this
a bug, or am I missing something?

Python 2.3.2 (#1, Oct 20 2003, 01:04:35)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
d1 = {'a':1}
d2 = {'b':2}
d3 = {'c':3}
l = [d1, d2, d3]
d4 = reduce(lambda x, y: x.update(y), l) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'update' d4 = reduce(lambda x, y: x.update(y), l, {})

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'update'

- Steve.
Jul 18 '05
226 12760
an***@vredegoor .doge.nl (Anton Vredegoor) wrote:
def factorial(x):
b = _Memo.biggest
if x > b: return reduce(mymul, xrange(b+1,x+1) , b)
return _Memo.facdict[x]


Sorry, this part should be:

def factorial(x):
b = _Memo.biggest
if x > b:
start = _Memo.facdict[b]
return reduce(mymul, xrange(b+1,x+1) , start)
return _Memo.facdict[x]
Jul 18 '05 #31
Anton Vredegoor wrote:
an***@vredegoor .doge.nl (Anton Vredegoor) wrote:
def factorial(x):
b = _Memo.biggest
if x > b: return reduce(mymul, xrange(b+1,x+1) , b)
return _Memo.facdict[x]


Sorry, this part should be:

def factorial(x):
b = _Memo.biggest
if x > b:
start = _Memo.facdict[b]
return reduce(mymul, xrange(b+1,x+1) , start)
return _Memo.facdict[x]


The horrid complication of this example -- including the global side
effects, and the trickiness that made even you, its author, fall into such
a horrid bug -- is, I think, a _great_ testimonial to why reduce should go.
I would also include in this harrowing complexity the utter frailty of the
(textually separated) _Memo / mymul coupling, needed to maintain
_Memo's unstated invariant. This code is as close to unmaintainable,
due to complexity and brittleness, as Python will allow.

I will gladly concede that reduce IS hard to beat if your purpose is to
write complex, brittle, hard-to-maintain code.

Which is exactly why I'll be enormously glad to see the back of it, come
3.0 time, and in the meantime I heartily suggest to all readers that (like,
say, apply) it is best (_way_ best) avoided in all new code.
Alex

Jul 18 '05 #32
In article <TE************ *********@news1 .tin.it>, Alex Martelli
<al*****@yahoo. com> writes
.....
I will gladly concede that reduce IS hard to beat if your purpose is to
write complex, brittle, hard-to-maintain code.

Which is exactly why I'll be enormously glad to see the back of it, come
3.0 time, and in the meantime I heartily suggest to all readers that (like,
say, apply) it is best (_way_ best) avoided in all new code. .....

I don't understand why reduce makes the function definition brittle. The
code was brittle independently of the usage. Would a similar brittle
usage of sum make sum bad?

I really don't think reduce, map etc are bad. Some just don't like that
style. I like short code and if reduce, filter et al make it short I'll
use that.

As for code robustness/fragility how should it be measured? Certainly I
can make any code fragile if I keep randomly changing the language
translator. So code using reduce is fragile if we remove reduce.
Similarly sum is fragile when we intend to remove that. Code is made
robust by using features that stay in the language. Keep reduce and
friends and make Python more robust.
Alex


--
Robin Becker
Jul 18 '05 #33
Alex Martelli <al*****@yahoo. com> wrote:
I will gladly concede that reduce IS hard to beat if your purpose is to
write complex, brittle, hard-to-maintain code.


Answering in the same vein I could now concede that you had
successfully distracted from my suggestion to find a better example in
order to demonstrate the superiority of recursive techniques over
iterative solutions in programming memoization functions.

However I will not do that, and instead concede that my code is often
"complex, brittle, hard-to-maintain". This probably results from me
being Dutch, and so being incapable of being wrong, one has to mangle
code (and speech!) in mysterious ways in order to simulate mistakes.

I'd like to distance myself from the insinuation that such things
happen on purpose. It was not necessary to use reduce to show an
iterative memoization technique, but since the thread title included
reduce I felt compelled to use it in order to induce the reader to
find a better example of recursive functions that memoize and which
cannot be made iterative.

This would generate an important precedent for me because I have
believed for a long time that every recursive function can be made
iterative, and gain efficiency as a side effect.

By the way, there is also some other association of reduce besides the
one with functional programming. Reductionism has become politically
incorrect in certain circles because of its association with
neopositivism and behavioristic psychology.

I would like to mention that there is also a phenomenologica l
reduction, which contrary to neopositivistic reduction does not try to
express some kind of transcendental idealism, in which the world would
be made transparent in some light of universal reason. Instead it
tries to lead us back to the world and the concrete individual
properties of the subjects under discussion.

Anton
Jul 18 '05 #34
Anton Vredegoor wrote:
...
find a better example of recursive functions that memoize and which
cannot be made iterative.

This would generate an important precedent for me because I have
believed for a long time that every recursive function can be made
iterative, and gain efficiency as a side effect.


Well, without stopping to ponder the issue deeply, I'd start with:

def Ack(M, N, _memo={}):
try: return _memo[M,N]
except KeyError: pass
if not M:
result = N + 1
elif not N:
result = Ack(M-1, 1)
else:
result = Ack(M-1, Ack(M, N-1))
_memo[M,N] = result
return result

M>=0 and N>=0 (and M and N both integers) are preconditions of the Ack(M, N)
call.

There is a substantial body of work on this function in computer science
literature, including work on a technique called "incrementaliza tion" which,
I believe, includes partial but not total iterativization (but I am not
familiar with the details). I would be curious to examine a totally
iterativized and memoized version, and comparing its complexity, and
performance on a few typical (M,N) pairs, to both this almost-purest
recursive version, and an incrementalized one.
Alex

Jul 18 '05 #35
Anton Vredegoor wrote:
find a better example of recursive functions that memoize and which
cannot be made iterative.

This would generate an important precedent for me because I have
believed for a long time that every recursive function can be made
iterative, and gain efficiency as a side effect.


Recursive memoization can be better than iteration when the recursion
can avoid evaluating a large fraction of the possible subproblems.

An example would be the 0-1 knapsack code in
http://www.ics.uci.edu/~eppstein/161/python/knapsack.py

If there are n items and size limit L, the iterative versions (pack4 and
pack5) take time O(nL), while the recursive version (pack3) takes time
O(min(2^n, nL)). So the recursion can be better when L is really large.

An example of this came up in one of my research papers some years ago,
http://www.ics.uci.edu/~eppstein/pubs/p-3lp.html
which involved a randomized recursive memoization technique with runtime
significantly faster than that for iterating through all possible
subproblems.

--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
Jul 18 '05 #36
Alex Martelli <al*****@yahoo. com> wrote:
def Ack(M, N, _memo={}):
try: return _memo[M,N]
except KeyError: pass
if not M:
result = N + 1
elif not N:
result = Ack(M-1, 1)
else:
result = Ack(M-1, Ack(M, N-1))
_memo[M,N] = result
return result

M>=0 and N>=0 (and M and N both integers) are preconditions of the Ack(M, N)
call.


Defined as above the number of recursions is equal to the return
value, because there is only one increment per call.

Have a look at the paper about the ackerman function at:

http://www.dur.ac.uk/martin.ward/martin/papers/

(the 1993 paper, halfway down the list, BTW, there's also something
there about automatically translating assembler to C-code, maybe it
would also be possible to automatically translate C-code to Python?
Start yet another subthread :-)

Another thing is that long integers cannot be used to represent the
result values because the numbers are just too big.

It seems possible to make an iterative version that computes the
values more efficiently, but it suffers from the same number
representation problem.

Maybe Bengt can write a class for representing very long integers as
formulas. For example an old post by François Pinard suggests that:

ackerman(4, 4) == 2 ** (2 ** (2 ** (2 ** (2 ** (2 ** 2))))) - 3

Anton
Jul 18 '05 #37
Georgy Pruss wrote:
"Alex Martelli" <al***@aleax.it > wrote in message
news:Bs******** *************** @news2.tin.it.. .
| <...>
| is way faster than "reduce(operato r.add, ..." -- and the advantage in
| speed *AND* simplicity grows even more when one considers how often
| that typical reduce is miscoded as "reduce(lam bda x, y: x+y, ..." or
| "reduce(int.__a dd__, ..." and the like.

What's the difference between operator.add and int.__add__?
operator.add just adds anything, not caring about the type of what
it's adding. Internally, it just reaches for the "addition function"
slot and calls that function, period.
Why is operator.add faster and "better" than int.__add__ if we deal
with integers?


int.__add__ must also check the type of its argument, and only call
the addition function if the argument is indeed integer, because
otherwise it must raise a TypeError. The type-checking is normally
needless overhead.

So, we can measure, for example:

alex@lancelot src]$ timeit.py -c -s'import operator' 'map(int.__add_ _,
xrange(999), xrange(999))'
1000 loops, best of 3: 730 usec per loop

[alex@lancelot src]$ timeit.py -c -s'import operator' 'map(operator._ _add__,
xrange(999), xrange(999))'
1000 loops, best of 3: 460 usec per loop

the 999 (useless) type-checks cost 270 microseconds, for a net of
about 270 nanoseconds per check; the 999 additions and the building
of the 999-elements result list cost another 460 microseconds, or
about 460 nanoseconds per operation-and-addition-to-list-of-results.
Alex

Jul 18 '05 #38
Alex Martelli wrote:
Erik Max Francis wrote:

But reduce isn't simply intended for adding up numbers. It's for doing
any kind of reduction.

However, so many of reduce's practical use cases are eaten up by sum,
that reduce is left without real use cases to justify its existence.


How about

import operator
seq_of_flag_int egers = [01020, 02300, 00132] #etc.
reduce(operator .or_, seq_of_integers )

My simple timing tests (cumulative time for 1000 trials, each with a
sequence of 1000 integers), show no significant difference between the
above and an alternative using a for loop and |=, but the above is
clearer to read.

I'm not claiming that the use case above is common, or particularly
useful. I'm just pointing out sum doesn't replace reduce unless the
function being applied is addition. Addition may be the most common
case, and in that case, sum is both clearer and faster. However, that
doesn't detract from the clarity and usefulness of reduce in the
remaining cases.

David

P. S. I've seen a lot of talk about removing old features from Python,
or specifically old built-ins, because of bloat. Does this "bloat"
reduce performance, or does it refer to the extra burden on someone
learning the language or reading someone else's code?

Jul 18 '05 #39
David C. Fox wrote:
...
However, so many of reduce's practical use cases are eaten up by sum,
that reduce is left without real use cases to justify its existence.
How about


....a typical example of *made-up* case follows...:
import operator
seq_of_flag_int egers = [01020, 02300, 00132] #etc.
reduce(operator .or_, seq_of_integers )

My simple timing tests (cumulative time for 1000 trials, each with a
sequence of 1000 integers), show no significant difference between the
above and an alternative using a for loop and |=, but the above is
clearer to read.
You may consider it "clearer to read", and I might opine differently
(apart from the typo/bug that you're reducing a sequence you never
defined, of course:-). That (necessary) trailing underscore in the
name of operator.or_ is quite unpleasant, for example. But I think
the real point is another.

If you're doing lots of bit-twidding in Python, you surely need to learn
such Python constructs as for and |= anyway.

With these can't-avoid-learning-them constructs, you can obviously
code a simple, elementary loop such as:
ored_flags = 0
for flags in all_the_flags:
ored_flags |= flags

Alternatively, you may learn _two more_ things -- that 'reduce' thingy
_plus_ the fact that module operator has an or_ function that does the
same job as | -- all in order to get an *equivalent* way to code the
same task?! Not to mention that what you end up coding this way is most
definitely NOT going to be any clearer than the simple, elementary loop
to any future maintainer of your code -- if your bit-twiddling code is
going to be maintained by somebody who doesn't understand for or | you
are in trouble anyway, friend, while -- given that reduce and operator.or_
give NO real advantages! -- it WOULD be perfectly possible for your future
maintainer to NOT be familiar with them.

I'm not claiming that the use case above is common, or particularly
useful. I'm just pointing out sum doesn't replace reduce unless the
function being applied is addition. Addition may be the most common
case, and in that case, sum is both clearer and faster. However, that
doesn't detract from the clarity and usefulness of reduce in the
remaining cases.
It's hard to detract from the clarity and usefulness of a construct
that never had much usefulness OR clarity in the first place. When
we've taken away just about all of its reasonably frequent use cases,
what remains? Essentially only a case of "more than one way to do-itis"
where in the "BEST" case the existence of 'reduce' and module operator
let you "break even" compared to elementary, simplest coding -- and
more often than not you can fall into traps such as those exemplified by
most reduce-defenders' posts on this thread.

P. S. I've seen a lot of talk about removing old features from Python,
or specifically old built-ins, because of bloat. Does this "bloat"
reduce performance, or does it refer to the extra burden on someone
learning the language or reading someone else's code?


A slightly larger memory footprint, and larger built-ins dictionaries,
can only reduce runtime performance very marginally. The "cognitive
burden" of having built-ins that "don't carry their weight", on the
other hand, is considered an issue *in Python*, because it doesn't fit
in with Python's general philosophy and worldview. Python is meant to
be a LEAN language (with a not-lean standard library of modules that
are specifically imported when needed); certain "legacy" features are
sub-optimal (and best removed, when the strict constraint of backwards
compatibility can be relaxed) because they interfere with that (and
built-ins are close enough to "the core language" that they _do_ need
to be weighed severely in terms of "how often will they be useful").

It's a conceptual wart that the only sincere response to this thread
subject can be "not much, really -- basically backwards compatibility,
and some people's preference for constructs they're used to, often in
preference to simpler or better performing ones, some of which didn't
happen to have been introduced yet when they learned Python"...:-).
Alex

Jul 18 '05 #40

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

Similar topics

181
8951
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.
16
2190
by: clintonG | last post by:
At design-time the application just decides to go boom claiming it can't find a dll. This occurs sporadically. Doing a simple edit in the HTML for example and then viewing the application has caused the application to go boom. Sometimes the page will compile and run using F5 and others not. So I do the web search tango looking around the blogs and the tuts and determine I should go into Temporary ASP.NET Files and delete the directory...
1
2814
by: mai | last post by:
Hi everyone, i'm trying to exhibit FIFO anomaly(page replacement algorithm),, I searched over 2000 random strings but i couldnt find any anomaly,, am i I doing it right?,, Please help,,,The following is the code,, #include <iostream> #include <string> #include <stdio.h> #include <stdlib.h> #include <ctime // For time()
7
3509
by: cnb | last post by:
This must be because of implementation right? Shouldn't reduce be faster since it iterates once over the list? doesnt sum first construct the list then sum it? ----------------------- reduce with named function: 37.9864357062 reduce with nested, named function: 39.4710288598 reduce with lambda: 39.2463927678 sum comprehension: 25.9530121845
0
9727
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
10982
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
10706
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
10331
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...
1
7880
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
7053
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5909
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4523
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
4116
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.