[Tutor] Generator function question?
Jacob S.
keridee at jayco.net
Sun May 8 20:02:00 CEST 2005
> import sys
>
> def neverEndingStatus(currentChar_ = '|'):
> while 1:
> if currentChar_ == '|':
> currentChar_ = '\\'
> elif currentChar_ == '\\':
> currentChar_ = '-'
> elif currentChar_ == '-':
> currentChar_ = '/'
> elif currentChar_ == '/':
> currentChar_ = '|'
> yield currentChar_
>
>
> x = neverEndingStatus()
>
> def Test1():
> for w in range(1, 100):
> sys.stderr.write('\b'+x.next())
########################################
> for z in range(1, 10000):
> z = z + 1
What on earth is the point of this? Why put a loop in there that does
nothing?
Are you just trying to take time?
########################################
> def Test2():
> for y in range(1, 10):
> sys.stderr.write('\b \nTesting'+str(y)+'\t')
> Test1()
>
> Test2()
import sys
from itertools import cycle
# nesl = Never ending status list
nesl = ["|","\\","-","/"]
a = cycle(nesl)
## ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ##
## | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ##
## This is just using itertools' cycle to automatically make the iterator
you were trying for ##
# Now we rewrite your test cases
def Test1():
sys.stderr.write("\b"+"\b".join(a.next() for x in range(1,100)))
## You realize that this will only give you 99 characters, not 100
def Test2():
for i in range(1,10): ## You realize again that this only runs 9
times...
sys.stderr.write("\b \nTesting %s\t" % y)
Test1()
Test2()
Well, this is not tested, but it shows that you can use itertools.cycle to
do what you want.
Also, the test cases are slightly neater (to me) too.
Okay, I'm done
Jacob
More information about the Tutor
mailing list