Generadores para los más pequeños

¡Hola a todos! Cuando estudiaba Python por mi cuenta, encontré suficiente material teórico sobre el lenguaje y sus capacidades. Sin embargo, incluso después de leer varios artículos en varios sitios y libros, muchos no cabían en mi cabeza (sí, estoy tan apretado). Los conceptos incomprensibles tuvieron que ser abarrotados "en la fe" sin una comprensión profunda, porque los ejemplos prácticos en los artículos eran difíciles para mí. Pasó el tiempo, me volví más experimentado, llegó la comprensión de problemas prácticos y en algún momento comencé a enseñar Python a mis amigos. A través de la tutoría, he descubierto que parece haber trazado un camino en el que los conceptos complejos se pueden explicar en términos simples.





Con respecto a toda la comunidad de TI en el Día del Niño y con la esperanza de poder ayudar a los principiantes a comprender la belleza y los beneficios de las cosas que son difíciles e incomprensibles a primera vista, estoy escribiendo mi artículo de debut.





Hoy quiero volver a hablar de generadores. ¡Entonces, a la batalla!





Entenderemos los conceptos y estableceremos la tarea.

Lo primero que debe tener siempre en cuenta cuando alguien le habla sobre los generadores de Python es no confundir "comprensiones" y "generadores de iteradores". El primero es un poderoso azúcar sintáctico para generar colecciones sobre la marcha, el segundo es una forma de recuperar valores bajo demanda. Hoy nos centraremos en el segundo.





, , : « !» , - .





      .
.

: (, , ..) -. - «». ( 3 10, - 10).





: , , . . , , , .





, :





  1. . .





  2. . .





. : , - - . , (-, , ) , - . , , . . , :)





:





    ,      .
, .

, , , . , . «», , , , - . .





:





-









20 .





40 .









30 .





50 .









25 .





5 .









15 .





35 .









10 .





25 .









30 .





35 .









30 .





50 .









20 .





15 .









15 .





15 .





Python. - . 0 100 000 000.





859 724 472 , 6 . , - , . , , . . : . ?





«» . , n , - . - -. , - . , .





, , , — . : next



, .





, , . , . , , , . , .





, , next: ,





: , 100 000 000 . 2 , — 10, (5) (3). «».





, next , -. - 100 000 000 120 ( — ), 0,00009 . , , , ( — ), .





:





  • - , , - . , , .





  • - , , . , . .





Python. , - , 0 n.





, (). , - . , 4, 2 . .





def skat(n): 
    """,     0  n""" 
    #     range,   range  -.
    res = []
    cnt = 0
    while cnt < n:
        res.append(cnt)
        cnt += 1
    return res

def first_eater(eda_list): 
""" """ 
    for eda in eda_list: 
        print(f"   {eda}  : ", str(eda)) 
      
      
def second_eater(eda_list): 
""" """ 
    for eda in eda_list: 
        print(f"   {eda}  : ", str(eda) * 4) 
      
      
def third_eater(eda_list): 
""" """ 
    for eda in eda_list: 
        print(f"   {eda}  : ", str(eda) * 10)
      
      
#  
eda_list = skat(100_000_000) 
#   
golod_1 = 2 
golod_2 = 3 
golod_3 = 4 
# 
first_eater(eda_list[:golod_1])
second_eater(eda_list[golod_1:golod_2 + golod_1])
third_eater(eda_list[golod_2 + golod_1:golod_2 + golod_1 + golod_3])

# ,     :
# >>>    0  :  0
# >>>    1  :  1
# >>>    2  :  2222
# >>>    3  :  3333
# >>>    4  :  4444
# >>>    5  :  5555555555
# >>>    6  :  6666666666
# >>>    7  :  7777777777
# >>>    8  :  8888888888
      
      



, : . , , . . , , . , , , pop



, ( ), .





, , — . ? . - (return



- ) ( return



None



). , Python return



, — yield



.





, :





def my_func_1():
  print("  ")
  return 1


def my_func_2():
  print("  ")
  yield 1
      
      



( , , ):





print(my_func_1)
print(my_func_2)

# ,     :
# >>> <function my_func_1 at 0x10c399950>
# >>> <function my_func_2 at 0x10c3a4290>
      
      



, my_func_1



my_func_2



, . . , :





print(my_func_1())
print(my_func_2())

# ,     
# >>>   
# >>> 1
# >>> <generator object my_func_2 at 0x108a702d0>
      
      



« ?» — .





« !» — .





, , yield



, - (generator-object



). , - — , , . ! , -, my_func_2



.





? ! Python next



( , ?), - ( -, , ) yield



, yield



. :





print(next(my_func_2()))

# ,     :
# >>> 1
      
      



! ! «... yield



...»? , , , - , yield



! - my_func_2



yield



:





def my_func_2():
    print("  ") 
    yield 1 
    print("   ") 
    yield 2 
    print("  !")

#     :
gen_o = my_func_2() #          generator-object

print(next(gen_o))
print(",       -  !") 
print(next(gen_o))

# ,     :
# >>>   
# >>> 1
# >>> ,       -  !
# >>>    
# >>> 2
      
      



, generator-object



next



yield



. , next



. «», . , , generator-object



, . ! .





next



:





gen_o = my_func_2()
print(next(gen_o))
print(",       -  !")
print(next(gen_o))
print(next(gen_o))

# ,     :
# >>> 1
# >>> ,       -  !
# >>>    
# >>> 2
# >>>   !
# >>> Traceback (most recent call last):
# >>> File "<  >", line 13, in <module>
# >>> print(next(gen_o))
# >>> StopIteration
      
      



, «» generator-object



. , yield



, . - , , StopIteration



.





: generator-object



«» . - «» . . generator-object



, my_func_2



.





   ,    "  ?"
, " ?"

. , , . , n, . , generator-object



, -, :





def skat(n):
    """,   -,    
        0  n"""
    cnt = 0
    while cnt < n:
        yield cnt
        cnt += 1


def first_eater(golod, skat):
    """ """
    while golod > 0:
        eda = next(skat)
        print(f"   {eda}    : ", eda)
        golod -= 1


def second_eater(golod, skat):
    """ """
    eda = next(skat)
    while golod > 0:
        print(f"   {eda}    : ", str(eda) * 4)
        golod -= 1


def third_eater(golod, skat):
    """ """
    eda = next(skat)
    while golod > 0:
        print(f"   {eda}    : ", str(eda) * 10)
        golod -= 1


skat_gen_obj = skat(100_000_000)
golod_1 = 2
golod_2 = 3
golod_3 = 4

try:
    first_eater(golod_1, skat_gen_obj)
    second_eater(golod_2, skat_gen_obj)
    third_eater(golod_3, skat_gen_obj)
except StopIteration:
    print("   !")

# ,     :
# >>>    0    :  0
# >>>    1    :  1
# >>>    2    :  2222
# >>>    2    :  2222
# >>>    2    :  2222
# >>>    3    :  3333333333
# >>>    3    :  3333333333
# >>>    3    :  3333333333
# >>>    3    :  3333333333
      
      



try - except



, . , , , .





     ,
,

«» ( , ). , , , . , , , (, «» :D) — generator-object



.





        ,         -
, -

- . , .





- . .





- , , .





, :





  • ,









  • , ,





    , :





  • ,





- , !





, :





  • , ( ) , , ,





: , , ..





,    -.
, -.

, ! , , — ). - , for



, .








All Articles