Domanda

def sp():
    i = 0
    while True:
        for j in range(i):
            yield(j)
        i+=1

This generator is supposed to yield all the integers in the range of (0, i), but it keeps returning 0 with every call of next(). Why?

Thanks.

È stato utile?

Soluzione

No, it doesn't. This is the output:

>>> s=sp()
>>> s
<generator object sp at 0x102d1c690>
>>> s.next()
0
>>> s.next()
0
>>> s.next()
1
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
3
>>> s.next()
0
>>> s.next()
1
>>> s.next()
2
>>> s.next()
3
>>> s.next()
4

which is exactly what you would expect. Each time, you start from 0 and go to whatever i is, then start back from 0 again up to the next value of i.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top