web服务器

生成器、迭代器

2018-12-05  本文已影响107人  GHope

生成器

迭代器

斐波那契数列和求素数的生成器和迭代器的实现

from math import sqrt


def is_prime(num):
    """判断是不是素数"""
    for factor in range(2, int(sqrt(num)) + 1):
        if num % factor == 0:
            return False
    return True


def prime(num):
    """素数生成器"""
    for val in range(2, num + 1):
        if is_prime(val):
            yield val


class Prime(object):
    """素数迭代器"""
    def __init__(self, number):
        self.number = number
        self.idx = 1

    def __iter__(self):
        return self

    def __next__(self):

        if self.idx < self.number:
            self.idx += 1
            if is_prime(self.idx):
                return self.idx
            return self.__next__()
        raise StopIteration()


class Fib(object):
    """斐波拉切数迭代器"""

    def __init__(self, num):
        self.num = num
        self.a, self.b = 0, 1
        self.idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.idx < self.num:
            self.a, self.b = self.b, self.a + self.b
            self.idx += 1
            return self.a
        raise StopIteration()


def fib(num):
    """斐波拉切数生成器"""
    a, b = 0, 1
    for _ in range(num):
        a, b = b, a + b
        yield a


def main():
    """主函数"""
    print('fibonacci number'.center(80, '-'))
    for val in Fib(20):
        print(val, end=' ')
    print('\n', '-' * 80, sep='')
    print('prime number'.center(80, '-'))
    for val in prime(100):
        print(val, end=' ')
    print('\n', '-' * 80, sep='')


if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读