Recursive generators are elegant

I just wrote a piece of code which drove home how simple and elegant generators in Python can be. I needed to loop through a *very large number* (lots and lots of digits) and though I needed only the string representation of the number, I couldn't write the loop in the typical fashion since the number was too large for Python to handle.

This is what I came up with. Does anyone have suggestions on how I can make this prettier?

def generate(prefix, remaining):
        if remaining ==0:
            yield prefix
        else:   
            for i in range(0,10):
                for number in generate(prefix + str(i), remaining-1):
                    yield number

for number in generate("", 25): #25 digit number
    print number


Comments:
No, that is the prettiest you can get in Python. Here is my version in C#. (how do you specify void as return type in Func<>?)
 
Srid - why not use the 'yield return' syntax in C# and do a direct translation?
 
Ah, thanks for the pointer. I am not yet aware of *all* the features in C#. I should properly and fully read about the language.
 
Answering my own question. To refer functions with Void return value, use 'Action' instead of 'Func'. via - http://blogs.msdn.com/wesdyer/archive/2007/12/22/continuation-passing-style.aspx
 
Post a Comment



<< Home

Archives

November 2004   January 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006   December 2006   January 2007   February 2007   March 2007   April 2007   May 2007   June 2007   July 2007   August 2007   September 2007   October 2007   December 2007   January 2008   February 2008   March 2008   April 2008   May 2008   June 2008   July 2008   August 2008