Why is my iterator returning extra \'None\' in the output. For the parameters/example below, I am getting [None,4,None]
instead of the desired [4]
Ca
Functions return None
if you don't have an explicit return
statement. That's what happens in __next__
when if (self.purchase[old])%(self.d) == 0:
isn't true. You want to stay in your __next__
until it has a value to return.
class Prizes(object):
def __init__(self,purchase,n,d):
self.purchase = purchase
self.length = len(purchase)
self.i = n-1
self.n = n
self.d = d
def __iter__(self):
return self
def __next__(self):
while self.i < self.length:
old = self.i
self.i += self.n
if (self.purchase[old])%(self.d) == 0:
return old+1
raise StopIteration
def superPrize(purchases, n, d):
return list(Prizes(purchases, n, d))
purchases = [12, 43, 13, 465, 1, 13]
n = 2
d = 3
print(superPrize(purchases, n, d))