yield

作者: JaedenKil | 来源:发表于2019-06-17 15:32 被阅读0次
    def fib(n):
        a, b = 0, 1
        for _ in range(n):
            a, b = b, a + b
            yield a
    
    
    def main():
        for val in fib(8):
            print(val)
    
    
    if __name__ == "__main__":
        main()
    
    1
    1
    2
    3
    5
    8
    13
    21
    

    def fib(n):
        if n == 1:
            return [1]
        elif n == 2:
            return [1, 1]
        else:
            # n >= 3
            arr = [1, 1]
            for i in range(2, n):
                arr.append(arr[i - 1] + arr[i - 2])
            return arr
    
    
    def main():
        fib(8)
    
    
    if __name__ == "__main__":
        print(fib(8))
    
    [1, 1, 2, 3, 5, 8, 13, 21]
    

    相关文章

      网友评论

        本文标题:yield

        本文链接:https://www.haomeiwen.com/subject/kgwafctx.html