#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, print_function, unicode_literals

import math
from itertools import islice


def gen_simple():
    print('in gen:1')
    yield 1
    print('in gen:2')
    yield 2
    print('in gen:3')
    yield 3


class PrimeNumbers(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end

    def is_prime(self, n):
        if n == 2:
            return True
        elif (n < 2) or (n % 2 == 0):
            return False

        i = 3
        while i <= math.sqrt(n):
            if n % i == 0:
                return False
            i += 2
        return True

    def __iter__(self):
        for k in range(self.start, self.end + 1):
            if self.is_prime(k):
                yield k


class FloatRange(object):
    def __init__(self, start, end, step=0.1):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        t = self.start
        while t <= self.end:
            yield t
            t += self.step

    def __reversed__(self):
        t = self.end
        while t >= self.start:
            yield t
            t -= self.step


if __name__ == '__main__':
    case = gen_simple()
    assert case.__iter__() is case
    print(case.__next__())
    print('out')
    for each in case:
        print(each)

    for x in PrimeNumbers(1, 100):
        print(x)

    for x in reversed(FloatRange(1.0, 4.0, 0.5)):
        print(x)

    fp = open('/var/log/ufw.log')
    # slice in file opening
    for line in islice(fp, 2, 20, 2):
        print(line)

    lst = list(range(20))
    t = iter(lst)
    for x in islice(t, 5, 10):
        print(x)
    print('out')
    for k in t:
        print(k)
