liximomo
liximomo

Reputation: 388

the next() method in python generator works weird

def conflict(state, nextX):
    nextY = len(state)
    for i in range(nextY):
        if abs(state[i]-nextX) in (0, nextY-i):
            return True
    return False

def queens(num=8, state=()):
    for pos in range(num):
        if not conflict(state, pos):
            if len(state) == num-1:
                yield (pos,)
            else:
                results=queens(num, state + (pos,))
                for res in results:
                    yield (pos,) + res 

print list(queens(8))

It‘s a solution of the eight queens,which works well.But when i did a little change.it’s becoming weird all about the next() method in python Generator.

def conflict(state, nextX):
    nextY = len(state)
    for i in range(nextY):
        if abs(state[i]-nextX) in (0, nextY-i):
            return True
    return False

def queens(num=8, state=()):
    for pos in range(num):
        if not conflict(state, pos):
            if len(state) == num-1:
                yield (pos,)
            else:
                results=queens(num, state + (pos,))
                for res in results:
                    yield (pos,) +results.next()   //here is the change. res -->results.next()  

print list(queens(8))

It's just print a [ ]. How embarrassed i am! I can't understand why the next() method works in any other situations but not here.

Upvotes: 1

Views: 292

Answers (1)

ecatmur
ecatmur

Reputation: 157334

What were you expecting to happen?

When you call next on a generator, it advances the generator and returns the next item. Your base case (len(state) == num-1) only yields a single item, so in that case it will advance the iterator, receive StopIteration, and terminate the loop, so you won't get any results back.

The root problem is that you're trying to advance an iterator while looping over it; that's unlikely to work well.

Upvotes: 3

Related Questions