Python: iterators and generators

Fibonacci sequence

Sequence recurrence formula:
fib(0)=1
fib(1)=1
fib(n)=fib(n-1)+fib(n-2) (n>=2)

def fib(n):
    if n==1 or n==2:
        return 1
    return fib(n-1)+fib(n-2)

# Output the value of Fibonacci sequence with n=10
print(fib(10))

55

Calculate factorial

1. for loop statement

a=1
n=5
for i in range(1,n+1):
    a = a * i
print(a)

120

2. Recursion of function

def f(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * f(n-1)
print(f(5))

120

3. reduce() function

from functools import reduce
n = 5
print(reduce(lambda x,y:x * y,range(1,n+1)))

120

1 iteratable objects and iterators

In Python, "iteratable object" and "iterator" are two different and related concepts.
(1) Functions that can receive "iteratable objects" can receive "iterators";
(2) The Python built-in function iter() can be used to convert an "iteratable object" into an "iterator".

  • Iteratable object: an object that can act directly on a circular statement (such as a for statement).
  • iterator: can be called by the built-in function next() and continuously return the next value object.

1.1 iteratable objects are not necessarily iterators

myList = [1,2,3,4,5]
next(myList)

TypeError Traceback (most recent call last)
in
1 myList = [1,2,3,4,5]
----> 2 next(myList)

TypeError: 'list' object is not an iterator

  • Reason for error reporting: myList is iterable, not iterator
  • Judgment method: use the built-in function isinstance() and the collections module
myList = [1,2,3,4,5]
next(myList)
from collections import iterable
isinstance(myList,iterable)

TypeError Traceback (most recent call last)
in
1 myList = [1,2,3,4,5]
----> 2 next(myList)
3 from collections import iterable
4 isinstance(myList,iterable)

TypeError: 'list' object is not an iterator

isinstance() function to determine whether an object is a known type, similar to type().

  • type() does not consider a subclass as a parent type and does not consider inheritance.
  • isinstance () will consider the subclass as a parent type and consider the inheritance relationship.
class A:
    pass
 
class B(A):
    pass
 
isinstance(A(), A)    # returns True
type(A()) == A        # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

Class is used to define A class, indicating that A is A kind, B is A kind, and A is A subclass of B.

1.2 converting iteratable objects to iterators -- built in function iter()

myIterator = iter(myList)
print(next(myIterator))
print(next(myIterator))
print(next(myIterator))

1
2
3

  • Method of traversing iterator contents -- built-in function next()

2 generator and iterator

A generator is a function that generates a new iterator. It is different from ordinary functions as follows.
(1) Use the yield statement instead of the return statement;
(2) Not "calculate now", but "lazy calculation" -- when the generator is called, it is not executed immediately, but postponed until each element needs to be called.

2.1 definition method of generator

The definition method of generator is different from that of general functions, using yield.

def myGen():
    x = range(1,11)
    for i in x:
        yield i+2

2.2 characteristics of generator

(1) The generator will not be returned immediately because it follows the "lazy calculation" mode.

def myGen():
    x = range(1,11)
    for i in x:
        yield i+2
myGen()

<generator object myGen at 0x0000025928FDFBA0>

(2) Only when the element is called will it be executed

for x in myGen():
    print(x,end=",")

3,4,5,6,7,8,9,10,11,12,

Tags: Python

Posted on Mon, 04 Oct 2021 20:35:36 -0400 by TAViX