user6535501
user6535501

Reputation:

linked list returning none when specified not too

I'm creating a singly linked list that returns odd numbers in a given range, instead of returning 1, 3, 5, etc it is returning 1, None, 3, None, 5, etc. I want to make it so that it stops returning None and only odd numbers.

class Odds:
    def __init__(self,end):
        self.__start = 1
        self.__end = end

    def __iter__(self):
        return OddsIterator(self.__end)

class OddsIterator:
    def __init__(self,finish): 
        self.__current = 0
        self.__step = 1
        self.__end = finish

    def __next__(self):
        x = None
        if self.__current > self.__end:
            raise StopIteration 
        else:
            self.__current += self.__step 
            if (self.__current - self.__step + 1) % 2 != 0:
                x = self.__current - self.__step + 1
        if x != None:
            return x 

Upvotes: 0

Views: 289

Answers (1)

Jeremy McGibbon
Jeremy McGibbon

Reputation: 3785

The reason None is being returned is that it's possible to reach the end of __next__ without a return statement, in which case any Python function returns None. The solution here is to set self.__step = 2 and self.__current = 1 when you initialize. You can also remove the if x != None:, since it does nothing. There are some other small changes I've made below to fit with this new definition of self.__current. Currently the code below will not include the final value, if you want it to then change self.__current >= self.__end to self.__current > self.__end.

class Odds:
    def __init__(self,end):
        self.__start = 1
        self.__end = end

    def __iter__(self):
        return OddsIterator(self.__end)

class OddsIterator:
    def __init__(self,finish):
        self.__current = 1
        self.__step = 2
        self.__end = finish

    def __next__(self):
        x = None
        if self.__current >= self.__end:
            raise StopIteration
        else:
            return_value = self.__current
            self.__current += self.__step
            return return_value

odds = Odds(21)
print(list(odds))

Upvotes: 2

Related Questions