likeAvirgin
likeAvirgin

Reputation: 83

How to fix this iterator?

I'm trying to write an iterator Digits(n) that generates digits of a natural number n in reverse order. Here's my code so far:

class Digits:

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

    def __iter__(self):
        return self

    def __next__(self):
        if self.n < 10:
            return self.n
        return self.n // 10

Output should be:

>>> print([x for x in Digits(1337)])
[7, 3, 3, 1]

I feel I should implement somewhere self.n % 10 (I hope) , but I don't know where. Any suggestions?

Upvotes: 0

Views: 65

Answers (3)

bipll
bipll

Reputation: 11940

You never actually modify the value, so don't iterate it. Try something like

def __next__(self):
   if self.n == 0:
       raise StopIteration()
   ret_val = self.n % 10
   self.n = //= 10
   return ret_val

Upvotes: 0

Balaji Ambresh
Balaji Ambresh

Reputation: 5037

Does this help?

class Digits:

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

    def __iter__(self):
        return self

    def __next__(self):
        if self.n == 0:
            raise StopIteration
        digit = self.n % 10
        self.n  = self.n // 10
        return digit

print([x for x in Digits(1337)])

Output:

[7, 3, 3, 1]

Upvotes: 3

phipsgabler
phipsgabler

Reputation: 20950

Just for completeness: it is rarely preferred to self-implement an iterator with __next__ instead of a generator with yield:

def digits(n):
    while n > 10:
        yield n % 10
        n //= 10
    yield n

This also relieves you from having to raise StopIteration manually.

Upvotes: 3

Related Questions