Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Iterator returns None

Here is my code:

class Prizes(object):
    def __init__(self, purchases, n, d):
        self.p = purchases
        self.n = n
        self.d = d
        self.x = 1

    def __iter__(self):
        return self

    def __next__(self):
        print(self.x)

        if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0:
            self.x = self.x + 1
            return self.x - 1
        elif self.x > len(self.p):
            raise StopIteration

        self.x = self.x + 1

def superPrize(purchases, n, d):
  return list(Prizes(purchases, n, d))

An example of usage:

superPrize([12, 43, 13, 465, 1, 13], 2, 3)

The output should be:

[4]

But actual output is:

[None, None, None, 4, None, None].

Why does it happen?

like image 294
Avo Asatryan Avatar asked Aug 28 '17 00:08

Avo Asatryan


1 Answers

Your problem is your implementation of __next__. When Python calls __next__, it will always expect a return value. However, in your case, it looks like you may not always have a return value each call. Thus, Python uses the default return value of a function - None:

You need some way to keep program control inside of __next__ until you have an actually return value. This can be done using a while-loop:

def __next__(self):
    while True:
        if self.x % self.n == 0 and self.p[self.x - 1] % self.d == 0:
            self.x = self.x + 1
            return self.x - 1
        elif self.x > len(self.p):
            raise StopIteration
        self.x = self.x + 1
like image 137
Christian Dean Avatar answered Sep 30 '22 10:09

Christian Dean