Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping over values in a generator function

I am writing a generator function that gives me alpha-characters, like so,

def gen_alphaLabels():
    a = range(65,91)
    for i in a:
        yield chr(i)

k = gen_alphaLabels()
for i in range(26):
    print k.next(),

This yields,

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

This works....

I would the function to skip over some characters that in a donotInclude list. I could do this is outside the generator, like so,

k = gen_alphaLabels()
donotInclude = ['D','K','J']
for i in range(26):
    r = k.next()
    if r not in donotInclude:
        print r,

This yields the desired result of skipping over 'D','K' and 'J'

A B C E F G H I L M N O P Q R S T U V W X Y Z

Is there a way include the logic relating to skipping over characters in the generator function? Some thing along the lines of

def gen_alphaLabels():
    a = range(65,91)
    for i in a:
        r = chr(i)
        if r in donotInclude:
            yield self.next()
        else: 
            yield r
like image 709
nitin Avatar asked Sep 04 '13 17:09

nitin


2 Answers

Without using continue + a little shortening of code:

def gen_alphaLabels(donotInclude):
    for i in range(65,91):
        char = chr(i)
        if char not in donotInclude:
            yield char
like image 109
Joohwan Avatar answered Oct 23 '22 05:10

Joohwan


continue to the rescue:

def gen_alphaLabels():
    a = range(65,91)
    for i in a:
        r = chr(i)
        if r in donotInclude:
            continue
        yield r
like image 36
RickyA Avatar answered Oct 23 '22 05:10

RickyA