ASm
ASm

Reputation: 389

Using an iterator in python?

I have just learned about iterators in Python however I am having a hard time implementing them.

I am trying to write a class to so that this loop works:

  odds = OddNumbers(13)
  for i in odds:
      print(i) 

I want to write an iter() function and next() function to do this.

So far I have:

class OddNumbers:

    def __init__(self, number):
        self.number = number

    def __iter__(self):
        return self

    def __next__(self):
        current = self.number
        if self.number%2 == 0:
            return current
        else:
            raise StopIteration

But at the moment this is returning nothing. I expect the output to be

1
3
5
7
9
11
13

Help?

Upvotes: 2

Views: 470

Answers (4)

Jason DeBolt
Jason DeBolt

Reputation: 17

This will give you an iterator-like object which provides even or odd numbers. However, it won't satisfy your for loop semantics as it is not a true iterator.

class NumberIterator(object):
    """Returns simple even/odd number iterators."""
    def __init__(self, current):
        self.current = current
    def next(self):
        self.current += 2
        return self.current
    @classmethod
    def getOddIterator(cls):
        return cls(-1) # start at 1
    @classmethod
    def getEvenIterator(cls):
        return cls(0) # start at 2


    odd_numbers = NumberIterator.getOddIterator()
    even_numbers = NumberIterator.getEvenIterator()

    odd_numbers.next() # Returns 1
    odd_numbers.next() # Returns 3

Upvotes: 0

sberry
sberry

Reputation: 131968

There is probably a much cleaner way of doing this, but here is a quick stab:

class OddNumbers:

    def __init__(self, number):
        self.number = number

    def __iter__(self):
        self.current = self.number
        return self

    def __next__(self):
        if self.current > 0:
            if self.current % 2 == 0:
                self.current -= 1
            self.current -= 1
            return self.current + 1
        raise StopIteration

Upvotes: 0

Brent Washburne
Brent Washburne

Reputation: 13138

You need another variable to track the current number:

def __init__(self, number):
    self.number = number
    self.current = 1

Then you need to compare it with the ending number, and maybe increment it:

def __next__(self):
    if self.current > self.number:
        raise StopIteration
    current = self.current
    self.current += 2
    return current

Upvotes: 1

augurar
augurar

Reputation: 13016

Your object needs to keep track of its state and update it when __next__ is called.

class OddNumbers(object):
    def __init__(self, number):
        self.current = ...
        self.number = number

    def __iter__(self):
        return self

    def __next__(self):
        # Update self.current
        # If the limit has been reached, raise StopIteration
        # Otherwise, return something

Upvotes: 3

Related Questions