By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,403 Members | 1,089 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,403 IT Pros & Developers. It's quick & easy.

what are generators?

P: n/a
I'm looking for a cool trick using generators. Know any exercises I
can work?
Mar 24 '08 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On Mar 24, 8:17*am, castiro...@gmail.com wrote:
I'm looking for a cool trick using generators. *Know any exercises I
can work?
Simple one the comes to mind is flattening a list:
>>list(flatten([1, [[2], 3], [[[4]]]]))
[1, 2, 3, 4]
>>>
HTH,
--
Miki <mi*********@gmail.com>
http://pythonwise.blogspot.com
Mar 26 '08 #2

P: n/a
On Mar 25, 7:36*pm, Miki <miki.teb...@gmail.comwrote:
On Mar 24, 8:17*am, castiro...@gmail.com wrote:
I'm looking for a cool trick using generators. *Know any exercises I
can work?

Simple one the comes to mind is flattening a list:
>list(flatten([1, [[2], 3], [[[4]]]]))
[1, 2, 3, 4]
I don't think it's well-defined. (But this is impossible and useless
calling.) CMIIW?

This is generic:
>>def f():
... __gen= None
... def g():
... i= 0
... while 1:
... i+= 1
... yield __gen( i )
... def set( gen ):
... nonlocal __gen
... __gen= gen
... return g, set
...
>>a, set= f()
b= a()
set( lambda x: print( x ) )
next( b )
1
>>next( b )
2
>>next( b )
Mar 27 '08 #3

P: n/a
On Mar 27, 6:19*am, castiro...@gmail.com wrote:
On Mar 25, 7:36*pm, Miki <miki.teb...@gmail.comwrote:
On Mar 24, 8:17*am, castiro...@gmail.com wrote:
I'm looking for a cool trick using generators. *Know any exercises I
can work?
Simple one the comes to mind is flattening a list:
>>list(flatten([1, [[2], 3], [[[4]]]]))
[1, 2, 3, 4]

I don't think it's well-defined. *(But this is impossible and useless
calling.) *CMIIW?

This is generic:
Revise:
>>def f():
... __gen= None
... def set( gen ):
... nonlocal __gen
... __gen= gen
... yield set
... i= 0
... while 1:
... i+= 1
... yield __gen( i )
...
>>a= f()
set= next( a )
set( lambda x: print( x ) )
next( a )
1
>>next( a )
2
>>next( a )
3
>>>
Mar 27 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.