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?
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With