1

I try to create a generator in python who returns this :

itemList = []for i in myGenerator(12):    itemList.append(i)print itemList>>> [0 0.334, 1, 2, 3, 4, 5, 6, 7, 8, 8.667, 9]

This is what I have at the moment :

def myGenerator(index) :    indexList = xrange(index)    for i in indexList :        if i == 0:            yield 0        elif i == 1:            yield i/3.0        elif i == indexList[-2]:            yield indexList[-3] - (1 / 3.0)        elif i == indexList[-1]:             yield i-2        else :            yield i-1for i in myGenerator(12):    print(i)

But it seems not clean ... Is there another way around?

unkulunkulu's user avatar
unkulunkulu
12k2 gold badges34 silver badges49 bronze badges
askedAug 22, 2012 at 9:28
MObject's user avatar
4
  • You can't pass a generator to thexrange function; not sure what you wanted to achieve with that?CommentedAug 22, 2012 at 9:29
  • That was a mistake .. It's for a script who generate the position of NURBS CVs in Maya.CommentedAug 22, 2012 at 9:33
  • 1
    what exactly are you trying to do ? it seems like a very odd list to generateCommentedAug 22, 2012 at 9:37
  • python wise, this seems ok, if you can write your algorithm in a more efficient way, i don't know, since I don't understand it.CommentedAug 22, 2012 at 9:40

2 Answers2

3

I'd construct the range piecewise:

from itertools import chaindef myGenerator(index):    return chain([0, 1 / 3.0], xrange(1, index - 3), [index - 3 - 1 / 3.0, index - 3])list(myGenerator(12))[0, 0.33333333333333331, 1, 2, 3, 4, 5, 6, 7, 8, 8.6666666666666661, 9]
answeredAug 22, 2012 at 9:39
ecatmur's user avatar
Sign up to request clarification or add additional context in comments.

Comments

3

If you want to stay close to your original idea but without the "if...elif...else" structure:

def myGenerator(index) :    yield 0    yield 1/3.0    for i in xrange(1, index-3):        yield i    yield index - 3 - 1/3.0    yield index - 3
answeredAug 22, 2012 at 12:42
MatthieuW's user avatar

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.