473,508 Members | 2,214 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

genexp reduce syntax in 2.5a1


On the python3000 mailing list there was some discussion of a "comprehension
syntax" for reduce.

This inspired me the following proof-of-concept in pure python 2.5a1, although I
don't know if it relies on an intended feature or a(n unintended) bug.

Cheers, BB
--

def ireduce(gen) :
"""
Generator expression syntax for reduce and generalizations

Usage examples:

- (yield) nothing as below if there is no seed value
*and* the expression consists of a single arithmetic op
ireduce(x+(yield) for x in range(101)) # famous Gauss example 5050 ireduce(x*(yield) for x in range(1,6)) 120

- if there is a seed, yield it (unless it's None)
ireduce(x*(yield 2) for x in range(1,6)) # 2*1*2*3*4*5 240 ireduce(x*(yield 2) for x in range(2,6)) # 2*2*3*4*5 240 ireduce(x*(yield 2) for x in range(6)) # 2*0*1*2*3*4*5 0

- if the seed is None, (yield INone) instead
ireduce((x,(yield INone)) for x in "for all good men".split()) ('men', ('good', ('all', ('for', None))))
ireduce([(yield INone),x] for x in "for all good men".split()) [[[[None, 'for'], 'all'], 'good'], 'men']

- do as below if you want no special seed and the operation to reduce
isn't a simple arithmetic operation
ireduce((x,(yield Seed(x))) for x in "for all good men".split()) ('men', ('good', ('all', 'for')))
ireduce(x+' '+(yield Seed(x)) for x in "for all good men".split()) 'men good all for'
ireduce({ x : (yield Seed(x))} for x in "for all good men".split()) {'men': {'good': {'all': 'for'}}}

- and notice these for a comparison
ireduce({ x : (yield x)} for x in "for all good men".split()) {'men': {'good': {'all': {'for': 'for'}}}}
ireduce({ x : (yield Seed(None))} for x in "for all good men".split())

{'men': {'good': {'all': None}}}
"""

cumulate = gen.next()
if cumulate is None :
cumulate = Neutral()
elif cumulate is INone :
cumulate = None
elif isinstance(cumulate,Seed) :
cumulate = cumulate.seed
gen.send(cumulate)
gen.next()
try :
while True :
cumulate = gen.send(cumulate)
gen.next()
except StopIteration :
return cumulate

class Neutral :
def __coerce__(self,other) :
self.other = other
return (self,self)

def __getattr__(self,attr) :
return lambda *x,**y : self.__dict__['other']

class INone : pass

class Seed :
def __init__(self,seed) :
self.seed = seed
Apr 18 '06 #1
0 1006

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

Similar topics

226
12318
by: Stephen C. Waterbury | last post by:
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) on linux2 Type...
2
1662
by: Bryan | last post by:
i thought that LC and genexp were supposed to be faster than map. i also thought i read somewhere in this group that the slowest looping mechanism in 2.4 is 20% faster than the fastest looping...
181
8601
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 ...
6
1502
by: Bengt Richter | last post by:
E.g., so we could write for x in seq if x is not None: print repr(x), "isn't None ;-)" instead of for x in (x for x in seq if x is not None): print repr(x), "isn't None ;-)"
22
1967
by: Cameron Laird | last post by:
QOTW: "... and to my utter surprise it worked." - Andrew Nagel on his move from wxPython to programming Tkinter in desperation "Python has more web application frameworks than keywords." - Skip...
7
1233
by: Paul Rubin | last post by:
I tried to code the Sieve of Erastosthenes with generators: def sieve_all(n = 100): # yield all primes up to n stream = iter(xrange(2, n)) while True: p = stream.next() yield p # filter out...
7
3487
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...
0
7231
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,...
0
7132
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...
0
7336
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,...
0
7401
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
5059
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
3211
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
3196
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1568
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 ...
0
432
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.