2018-06-29

from typing import Sequence


class ReverseSequence(object):
    def __init__(self, sequence: Sequence):
        self.sequence = sequence  # reference to container
        self.index = len(sequence)  # current index

    # Step 1. define __iter__ method whitch returns self.
    def __iter__(self):
        return self

    # Step 2. define __next__ method
    #             rasing StopIteration at the end of iteration.
    def __next__(self):
        if self.index > 0:
            self.index = self.index - 1  # next index
            return self.sequence[self.index]
        else:
            raise StopIteration


class ReverseSequenceGenerator(object):
    def __init__(self, sequence: Sequence):
        self.sequence = sequence
        self.index = len(sequence)

    def __iter__(self):
        while self.index > 0:
            self.index = self.index - 1
            yield self.sequence[self.index]
        raise StopIteration


assert list.__eq__(
    [element for element in ReverseSequence('spam')],
    [element for element in ReverseSequenceGenerator('spam')]
)

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]


class ReverseGenerator:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        while True:
            if self.index == 0:
                raise StopIteration
            self.index = self.index - 1
            yield self.data[self.index]


assert [s for s in Reverse('spam')] == [s for s in ReverseGenerator('spam')]

記事への反応(ブックマークコメント)

アーカイブ ヘルプ
ログイン ユーザー登録
ようこそ ゲスト さん