Avo Asatryan Avo Asatryan - 2 months ago 16
Python Question

Iterator returning several Nones

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))


For

purchases = [12, 43, 13, 465, 1, 13]
n = 2
d = 3
superPrize(purchases, n, d)


the output should be

[4]


But my actual output is

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


How can I fix these
None
s?

Answer Source

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