473,594 Members | 3,003 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 "comprehens ion
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+(yiel d) for x in range(101)) # famous Gauss example 5050 ireduce(x*(yiel d) for x in range(1,6)) 120

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

- if the seed is None, (yield INone) instead
ireduce((x,(yie ld 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,(yie ld 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(cumu late,Seed) :
cumulate = cumulate.seed
gen.send(cumula te)
try :
while True :
cumulate = gen.send(cumula te)
except StopIteration :
return cumulate

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

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

class INone : pass

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

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

Similar topics

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 "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3}
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 mechanism in 2.3. if i'm wrong about this, remembered wrong or did something wrong, please let me know. here are some timeit tests i did on my machine. notice that map is faster in both python versions and that LC24/LC23 is only a 5.5% speed...
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.
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 ;-)"
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 Montanaro (but probably others going back years) Frithiof Andreas Jensen writes frankly on use of SNMP and netconf: http://groups.google.com/group/comp.lang.python/msg/662032bf92670fd7
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 all multiples of p from stream stream = (q for q in stream if q%p != 0)
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
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...
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,...
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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,...
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...
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...
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();...
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...
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.