Aún no tienes acceso a esta clase

Crea una cuenta y continúa viendo este curso

Curso Profesional de Python

Curso Profesional de Python

Facundo García Martoni

Facundo García Martoni

La sucesión de Fibonacci

13/21
Recursos

Aportes 480

Preguntas 17

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

from time import sleep
class FiboIter():

    def __init__(self, max_number:int):
        self.max_number = max_number
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
    
    def __next__(self):

        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            
            if self.aux >= self.max_number:
                raise StopIteration
            
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux
        


if __name__ == "__main__":
    for element in FiboIter(39):
        print(element)
        sleep(0.1)

Mi aporte al reto! Saludos

No puse el output porque es lo mismo que lo visto en la clase, solamente que se detiene cuando llegamos al numero que le pasamos.

Adicionalmente a la sucesión de Fibonacci hice un iterador que obtiene los números primos que existen hasta cierto n. Me parece increíble lo que se puede hacer con los iteradores. 😮

Este es mi solucion, funciona con o sin numero maximo. Decidi hacerlo asi gracias a un comentario que mire.

import time

class FiboIter():
    
    def __init__(self, max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
        
    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter ==1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            self.counter += 1
            self.n1, self.n2 = self.n2, self.aux
            if not self.max:
                return self.aux, self.counter

            if self.max:
                if self.aux > self.max:
                    raise StopIteration
                else:
                    return self.aux, self.counter

if __name__ == '__main__':
    for element in FiboIter():
        print(element)
        time.sleep(.05)

Una duda que me surgio fue el de como acceder opcionalmente al contador, ya que en el codigo se agrega pero no encontre forma de acceder a el en el codigo como e esta. ademas de cuestionarme su empleo ya que no parece tener algun tipo de utilidad.

Una solución simple y eficaz 😁

Algo que descubrí al estar haciendo el reto es podemos inicializar un iterador solo con el método next, pero fallará porque no tendrá los atributos que declaremos en el metodo iter. Y lo curioso es que nosotros no podemos utilizar __iter__() para inicializar el iterador como haciamos con iter(objeto) .
En cambio con __next__() sí podremos ir avanzadando por cada elemento del iterador 👍

This is my code. Please comment any error did you’ll find.

<import time 

class Fibonacci():

    def __init__(self, nmax):
        self.nmax = nmax
        
    def __iter__(self):
        self.num1 = 0
        self.num2 = 1
        self.counter = 0 
        return self

            
    
    def __next__(self):

        if self.counter == 0:
            self.counter += 1 
            return self.num1

        elif self.counter == 1:
            self.counter += 1
            return self.num2
        
        else:

            self.aux = self.num1 + self.num2 

            # Like a break; if the aux > nmax: stop, nmax is the limit.
            if self.aux > self.nmax:
                print('Finished.')
                raise StopIteration
                
            self.num1, self.num2 = self.num2, self.aux 
            self.counter += 1 
            return self.aux 
        
        
def run():
  
    try:
        nmax = int(input('Introduce the max limit number that can iterate this function: \n'))
        
        if nmax > 0:
            fibonacci = Fibonacci(nmax)
            for element in fibonacci:
                print(f' \n{element}')
                time.sleep(1)

        elif nmax == 0:
            print(0)

        else:
            print('Introduce a positive number.') 
            run()
            
    except ValueError as ve:
        print('Only integer and positive numbers.')
        run()
   
if __name__ == '__main__':
    run()
   
    > 
import time

class FiboIter():
   
   def __init__(selft, max = None):
      if max == None:
         selft.max = None
      else:
         selft.max = max
   
   def __iter__(selft):
      selft.n1 = 0
      selft.n2 = 1
      selft.counter = 0
      return selft
   
   def __next__(selft):
      def fibo(): #funcion fibonacci
         selft.aux = selft.n1 + selft.n2
         #selft.n1 = selft.n2
         #selft.n2 = selft.aux
         selft.n1, selft.n2 = selft.n2, selft.aux
         selft.counter += 1
         return selft.aux
      
      if selft.counter == 0:
         selft.counter += 1
         return selft.n1
      elif selft.counter == 1:
         selft.counter += 1
         return selft.n2
      elif selft.max == None:
         return fibo() #ejecucion infinita
      elif selft.counter >= selft.max:
         raise StopIteration
      else:
         return fibo()#ejecucion controlada

if __name__ == "__main__":
   fibonacci = FiboIter()
   i  = 0
   for element in fibonacci:
      print(str(i) + " Vueltas")
      print(element)
      time.sleep(0.05)
      i += 1

Hola se aceptan comentarios, no soy nada experta…

import time

class FiboIter():

    def __init__(self, max=None):
        self.max = max

    def __iter__(self): 
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self 

    def __next__(self):
        if not self.max or self.counter <= self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration

#Visualizar en consola
if __name__ == '__main__':
    fibonacci = FiboIter(25)
    for idx, element in enumerate(fibonacci):
        print(idx, " ", element)
        time.sleep(0.05) 

Lo quise hacer de esta manera. Utilicé atributos privados en la clase agregando “__” al inicio de sus nombres. Me pareció correcto inicializar las variables de los números en el constructor y dejar solamente el contador en el método iter(). No se que opinen de esto último.

class Fibonacci:
    def __init__( self,upper ):
        self.__upper = upper
        self.__num1 = 0
        self.__num2 = 1

    def __iter__( self ):
        self.__counter = 0
        return self
        
    def __next__( self ):
        if self.__counter < self.__upper:
            returned = self.__num1
            self.__num1 = self.__num2
            self.__num2 += returned
            self.__counter += 1
            return returned
        else:
            raise StopIteration

if __name__ == '__main__':
    for i in Fibonacci(20):
        print(i,end=" ")


Este es mi aporte, entendí que el usuario debería llenar el máximo valor y este debe parar.

import time

class FiboIter():

    def __init__(self, max = int(input("Ingresa un valor: "))):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.cnt = 0
        return self

    def __next__(self):
        if not self.max or self.n1 + self.n2 <= self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else: 
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            
        else:
            raise StopIteration
        

if __name__ == "__main__":
    fibonacci = FiboIter()
    for element in fibonacci:
        print(element)
        time.sleep(1)
import time

class fiboIter():
    
    def __init__(self,max):
        self.max = max
    
    def __iter__(self):
        self.number1 = 0
        self.number2 = 1
        self.counter = 0
        return self
    
    def __next__(self):
        if self.counter == 0:
            self.counter +=1
            return self.number1
        elif self.counter == 1:
            self.counter +=1
            return self.number1
        elif self.number2 < self.max:
            self.aux = self.number1 + self.number2
            """ esto <self.number1 = self.number2
            self.number2 = self.aux> se puede reducir de la siguiente forma """
            
            self.number1, self.number2 = self.number2, self.aux
            self.counter +=1
            return self.aux
        else:
            raise StopIteration
        

if __name__ == "__main__":
    
    fibonacci = fiboIter(1597)
    
    for element in fibonacci:
        print(element)
        time.sleep(1)

Me gusta darle participación al usuario, puse el input limite para que pueda definirse:

if __name__ == "__main__":
     fibonacci = FiboIter()
     limite = int(input("Digita el tope maximo al cual quieres llegar: "))
     for element in fibonacci:
        if(element<=limite):
            print(element)
        else:
            raise StopIteration
        time.sleep(1)

Clase top!

Les comparto unos cambios sobre la función next los cuales reduce la cantidad de lineas utilizadas para el calculo de la sequencia

import time

class FiboIter():

    def __init__(self, max:int = None):
        self.max = max

    def __iter__(self):
        self.n1 = -1
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if(self.counter == self.max):
            raise StopIteration
        self.counter +=1
        result = self.n1 + self.n2
        self.n1, self.n2 = self.n2, result

        return result
    
if __name__ == '__main__':
    for element in FiboIter():
        print(element)
        time.sleep(0.5)

Reto cumplido 🚀

import time

class FiboIter():

    def __init__(self, max_number):
        self.max_number = max_number

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        return self

    def __next__(self):
        if self.max_number > 0:
            self.aux = self.n1
            self.n1, self.n2 =  self.n2, self.n1 + self.n2
            self.max_number -= 1
            return self.aux
        else:
            raise StopIteration


if __name__ == "__main__":
    number = int(input("Enter a quantity of fibonacci numbers to display: "))
    assert number > 0, "Must enter a bigger number than 0!!!"
    fibonacci = FiboIter(number)
    for element in fibonacci:
        print(element)
        time.sleep(0.25)

Mi resultado al reto:

import time 

class FiboIter():

    def __init__(self, max = None):
        if max < 0:
            raise ArithmeticError
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter > self.max:
            raise StopIteration
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1 
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux


if __name__ == "__main__":
    fibonacci = FiboIter(10)
    for element in fibonacci:
        print(element)      
        time.sleep(0.10)      

Reto

import time

class FiboIter():
    def __init__(self, MAX):
        self.MAX = MAX
        

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        
        return self
    

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux 
            self.counter += 1
            if self.MAX >= self.counter:
                return self.aux
            else:
                print(f"iteracciones {self.counter-1} ")
                raise StopIteration



if __name__ == "__main__":
    fibonacci = FiboIter(11)
    for element in fibonacci:
        print(element)
        time.sleep(0.5)

Al ver las soluciones, creo lo hice mal, aunque pienso que llega al objetivo, ya lo empiezo a modificar metiéndome con la clase para obtener una versión extra, adjunto los cambios que realice en el apartado de entry point:

if __name__ == "__main__":
    num = int(input("break counter: "))
    fibonnacci = FiboIter()

    for element in fibonnacci:
        if fibonnacci.counter == num:
            raise StopIteration
        else:
            print(element)
            time.sleep(1) 

Esta es mi solución al reto:

class FiboIter:
    def __init__(self, max_iter=0):
        self.max_iter = max(max_iter, 0)

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = -1
        return self

    def __next__(self):
        self.counter += 1

        if self.counter == self.max_iter:
            raise StopIteration

        if self.counter == 0 or self.counter == 1:
            return self.counter

        next_result = self.n1 + self.n2
        self.n1, self.n2 = self.n2, next_result
        return next_result

Aparte de tener una variable max_iter para el límite, también le agrego un valor de 0 por defecto y antes también me aseguro que no sea negativo, si es negativo se vuelve 0. También uní los dos condicionales para los 2 primeros casos.

Clase Fibonnaci

class Fibonacci():
    
    def __init__(self, max=None) -> None:
        self.max = max

    def __iter__(self):
        self.n0 = 0
        self.n1 = 1
        self.aux = 0
        return self

    def __next__(self):
        if not self.max or self.aux < self.max:
            if self.aux == 0:
                self.aux += 1 
                return self.n0
            elif self.aux == 1:
                self.aux += 1 
                return self.n1
            else:
                self.result = self.n0 + self.n1
                self.n0, self.n1 = self.n1, self.result
                self.aux += 1
                return self.result
        else:
            raise StopIteration

Archivo a ejecutar

from time import sleep
from Fibonacci import Fibonacci

for i in Fibonacci(10):
    print(i)
    sleep(0.5)

Salida de consola

0
1
1
2
3
5
8
13
21
34

Esta es mi solución, la verdad es que es muy fácil. Puse el número de conteo máximo dentro de la Clase:

import time

class FiboIter():

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.max = 100
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.counter > 1 and self.counter < self.max:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            # esto es swapping, el primer elemento se sustituye con el otro primer elemento
            self.counter += 1
            return self.aux
        else:
            raise StopIteration


if __name__ == "__main__":
    fibonacci = FiboIter()
    for element in fibonacci:
        print(element)
        time.sleep(0.01)
import time

class FiboIter():
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
    
    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            #self.n1 = self.n2
            #self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux
            
# 0 1 1 2 3 5 8 13 21 34 55

if __name__ == '__main__':
    n = int(input('Enter a number: '))
    
    fibonacci = FiboIter()
    for i in fibonacci:
        if i < n:
            print(i)
            time.sleep(0.05)
        else:
            break

Mi solución al reto. Funciona aunque no sé si es correcta:

import time


class FiboIter():

    def __init__(self, max = None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            if not self.max or self.aux <= self.max:
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            else:
                raise StopIteration


if __name__ == '__main__':
    fibonacci = FiboIter(100)	# Número de prueba

    for element in fibonacci:
        print(element)
        time.sleep(1)

Buenas a todos y muchas gracias.

import os
from time import sleep


def clearScreen():
    if os.name == 'posix':
        os.system('clear')
    elif os.name == 'ce' or os.name == 'nt' or os.name == 'dos':
        os.system('cls')


class FiboIter():

    def __init__(self, max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max or self.counter < self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration


if __name__ == '__main__':
    clearScreen()
    while True:
        try:
            number = int(
                input('\nEnter the maximum to return the numbers of the fibonacci sequence: '))
            assert number > 0, 'Enter a number greater than 0'
            fibonacci = FiboIter(number)
            for element in fibonacci:
                print(element)
                sleep(0.7)
            if element != number:
                break
        except ValueError:
            print('\nEnter integers and positive numbers')
        except AssertionError as ae:
            print(f'\n{ae}')

Un saludo.

dejo mi reto!!!

<import time

class FiboIter():

    def __init__(self, max) :
        self.max=max
    
    def __iter__(self):
        self.n1=0
        self.n2=1
        self.counter=0
        return self


    def __next__(self):
        if self.counter==0:
            self.counter+=1
            return self.n1
        elif self.counter==1:
            self.counter+=1
            return self.n2
        else:
            if self.counter<=self.max:
                self.aux= self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux # manera resumida de cambio
                self.counter+=1
                return self.aux
            else:
                raise StopIteration

if __name__=='__main__':
   
    for element in FiboIter(100):
        print(element)
        time.sleep(0.5)
> 

Reto listo

import time

class FiboIter():
    # constructor de la clase.
    def __init__(self, max=None):
        #self hace referencia al objeto futuro que voy a crear con esta clase.
        self.max = max

    # Método para tener elementos o atributos que voy a necesitar para que el iterador funcione.
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    # Método para tener la función "next" de Python.
    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.counter < self.max:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux
        else:
            raise StopIteration

if __name__ == "__main__":
    fibonacci = FiboIter(10)
    for element in fibonacci:
        print(element)
        time.sleep(0.5)

Hola, esta es mi contribuciónal reto de la clase:

import time

class FiboIter():

    def __init__(self, max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.aux2 = 0
        return self

    def __next__(self):
        if not self.max or self.aux2 <= self.max:
            if self.counter == 0:
                self.counter+=1
                self.aux2 = self.counter
                return self.n1
            elif self.counter == 1:
                self.counter+=1
                self.aux2 = self.counter
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                self.aux2 = self.n1 + self.n2
                return self.aux
        else:
            raise StopIteration

if __name__ == '__main__':
    fibonacci = FiboIter(1000)
    for element in fibonacci:
        print(element)
        time.sleep(0.5)

Decidí utilizar un segundo atributo auxiliar que es el que controla la iteración dentro del rango de número máximos establecido en el constructor.

class Fibonacci:
def init(self, max=None):
self.max = max

def __iter__(self):
    self.a = 0
    self.b = 1
    self.counter = 0
    return self

def __next__(self):
    if not self.max or self.a < self.max:
        self.counter += 1
        self.a, self.b = self.b, self.a + self.b
        return self.a
    else:
        raise StopIteration

if name == “main”:
import time
for i in Fibonacci():
print(i)
time.sleep(0.05)

Aporte
Levanto el StopIteration cuando la suma de los dos ultimos numeros es mayor o igual al maximo fijado.

import time

class FiboIter():

    def __iter__(self):
        #Definimos los elementos necesario para que el iterador
        #funcione
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.max = 20
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            if self.aux >= self.max:
                raise StopIteration
            else:
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux

if __name__ == "__main__":
    fibonacci = FiboIter()
    for element in fibonacci:
        print(element)
        time.sleep(1) #Esto pausa 1 segundo antes de pasar a siguiente vuelta
import time

class FiboIter():
    
    def __init__(self, max=None):
        self.max = max
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
        
    def __next__(self):
        if self.max == self.counter:
            raise StopIteration
        else:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux

if __name__ == '__main__':
    fibonacci = FiboIter(1)
    for element in fibonacci:
        print(element)
        time.sleep(1)

mi aporte

import time

class FiboIter():

    def __init__(self, max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max or self.counter <= self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration

if __name__ == '__main__':
    fibonacci = FiboIter(30)
    for element in fibonacci:
        print(element)
        time.sleep(1)
import time

class Fibonacci:

    def __init__(self, max: int):
        self.max= max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
    

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter ==1:
            self.counter+=1
            return self.n2
        else:
            if self.counter <= self.max:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            else:
                raise StopIteration

if __name__ == '__main__':
    fibonacci = Fibonacci(50)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)
import time

class Fiboiter():
    def __init__(self, max = 1000):
        self.max = max
        
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
  
    def __next__(self):
        if self.counter == 0 :
            self.counter += 1
            return self.n1
        elif self.counter == 1 :
            self.counter += 1
            return self.n2
        else :
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1,self.n2 = self.n2,self.aux #swaping para resumir las 2 líneas 19 y 20
            self.counter += 1
            if self.aux <= self.max:
                return self.aux
            else:
                raise StopIteration
    
            
if __name__ == '__main__':
    fibonacci = Fiboiter()
    for element in fibonacci:
        print(element)
        time.sleep(1)


Mi modesto aporte, ahí vamos aprendiendo poco a poco.

Mi código para el reto es el siguiente. No he podido hacer que la iteración se detenga cuando el valor máximo es cero. Si alguien se da cuenta de mi error, agradecería que me lo pueda indicar. Gracias.

import time


class FiboIter():

    def __init__(self, max = None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            if self.counter == 0 and self.n1 <= self.max:
                self.counter += 1
                return self.n1
            elif self.counter == 1 and self.n2 <= self.max:
                    self.counter += 1
                    return self.n2
            elif self.counter > 1:
                self.aux = self.n1 + self.n2
                if self.aux <= self.max:
                    # self.n1 = self.n2
                    # self.n2 = self.aux
                    self.n1, self.n2 = self.n2, self.aux
                    self.counter += 1
                    return self.aux
                else:
                    raise StopIteration
            else:
                raise StopIteration


if __name__ == '__main__':
    fibonacci = FiboIter(1)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)

Ya hice la corrección, espero que les sirva, en caso de que el usuario no ingrese un límite:

import time

class FiboIter():

    def __init__(self, max: int = None) -> None:
        self.max = max

    def __iter__(self) -> int:
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.limit = max
        return self

    def __next__(self) -> int:
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else: 
            self.aux = self.n1 + self.n2
            
            if self.max == None or self.aux <= self.max:
                # Swaping
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux         
            else:
                raise StopIteration


if __name__ == "__main__":
    try:
        fibonacci = FiboIter()
        for element in fibonacci:
            time.sleep(0)
            print(element)
        
    except StopIteration:
        print("No puedo continuar, he alcanzado el límite")

Mi aporte del reto

import time

class Fibonacci_Iter:
    def __init__(self, max = None):
        self.max = max
    def __iter__(self):
        self.number1 = 0
        self.number2 = 1
        self.counter = 0
        return self
    
    def __next__(self):
        
        if self.max and self.counter <= self.max - 1:

            if self.counter == 0:
                self.counter += 1
                return self.number1
            elif self.counter == 1:
                self.counter += 1
                return self.number2
            else: 
                self.aux = self.number1 + self.number2
                self.number1, self.number2 = self.number2, self.aux
                self.counter += 1
                return self.aux
        else: 
            raise StopIteration
def run():
    max = 0
    while max <= 0:
        try:
            max = int(input('¿Cuántos números de la secuencia Fibonacci quiere ver? '))
        except ValueError:
            print('Valor no válido')
    
    fibonacci = Fibonacci_Iter(max)
    
    for element in fibonacci:
        print(element)
        time.sleep(0.2)

if __name__ == '__main__':
    run()

Hice el código que me devuelva iteraciones hasta la cantidad del valor máximo.

from time import sleep

class FibonacciIter:

    def __init__(self, max_iter:int):
        self.max_iter = max_iter
        
    def __iter__(self):
        self.a = 0
        self.b = 1
        self.cont = 0
        return self

    def __next__(self):
        if self.cont ==0:
            self.cont+=1
            return self.a
        elif self.cont ==1:
            self.cont+=1
            return self.b
        else:
            if self.cont <=self.max_iter:
                self.cont+=1
                c = self.a + self.b
                self.a, self.b = self.b, c
                return c
            else:
                raise StopIteration

def run():
    res_fibonacci = FibonacciIter(7)
    for i in res_fibonacci:
        print(i)
        sleep(1)


if __name__ == '__main__':
    run()

Se logra enviando el valor maximo a la funcion y haciendo el if hasta que el contador sea mayor o igual al numero enviado

import time

class FiboIter():

    def __init__(self, max: int):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max or self.counter <= self.max: 
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration

if __name__ == '__main__':
    fibonacci = FiboIter(10)
    for element in fibonacci:
        print(element)
        time.sleep(0.2)

Me costó mucho pero lo logré 😄

import time

class FiboIter():

    def __init__(self, max = None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 0
        return self

    def __next__(self):
        if self.n2 == 0:
            self.n2 += 1
            return 0
        self.n2 = self.n2 + self.n1
        self.n1 = self.n2 - self.n1
        if self.max is not None:
            if self.n1 > self.max:
                raise StopIteration
        return self.n1


if __name__ == '__main__':
    fibonacci = FiboIter(8)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)

Les adjunto mi aporte !!

Iterador para generar la secuencia de Fibonacci.

Usando ‘class’ y ‘while / try’

class FiboIter:
def init(self, max=None):
self.max = max

def __iter__(self):
    self.num1 = 0
    self.num2 = 1
    self.contador = 0
    return self

def __next__(self):
    if self.contador < self.max:
        self.sal = self.num1
        self.aux = self.num1 + self.num2
        self.num1, self.num2 = self.num2, self.aux
        self.contador += 1
        return self.sal
    else:
        raise StopIteration

if name == “main”:
fibonacci = FiboIter(10)
x = iter(fibonacci)

while True:
    try:
        print(x.__next__())
    except StopIteration:
        break

Buenas tardes compañeros a continuacion les presento mi aporte 😃 :

class fibo_iter():

    def __init__(self, maxi = None):
        self.maxi = maxi

    def __iter__(self):
        self.num1 = 0
        self.num2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.maxi or (self.num1 + self.num2) <= self.maxi:
            if self.counter == 0:
                aux = self.num1
                self.counter +=1
                return aux

            elif self.counter == 1:
                aux = self.num2
                self.num1 = self.num2
                self.counter +=1
                return aux
            
            else:
                aux = self.num1 + self.num2
                self.num1, self.num2 = self.num2, aux
                self.counter += 1
                return aux
                
        else:
            raise StopIteration


if __name__ == "__main__":
    fibonacci = fibo_iter(100)
    for element in fibonacci:
        print(element)
        print("\n")

La verdad es que al principio iba a generar el atributo dentro del objeto, pero lo hice de la forma mas simple que había. Espero que los ayude

Solución al reto.

import time

class fiboIter():

    def __init__(self,max=None):
        self.max=int(max)

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max or self.counter < self.max:
            if self.counter == 0:
                self.counter +=1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration

if __name__ == '__main__':
    fibonacci = fiboIter(max=0)
    for element in fibonacci:
        print(element)
        time.sleep(0.5)
        

Solo me queda la duda de que al pasar el maximo como 0, el programa continua trabajando.

Hola, esta es mi solución, sin embargo alcanza a imprimir el ultimo número superior al máximo:

import time

class FiboIter():

    def __init__(self, max=None):
        max =  int(input("Ingresa un número máximo: "))      
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
    
    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.n2 < self.max and self.n1 < self.max: 
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux
        else:
            raise StopIteration

if __name__ == "__main__":
    fibonacci = FiboIter()
    for element in fibonacci:
        print(element)
        # time.sleep(0.5)

La línea

self.count += 1

se pudiera escribir una sola vez en la función, ya que en cualquier condición que entre se hace esa suma.

Mi aporte para poder agregar el numero máximo directo en consola

import time

max_number = int (input ("ingrese un numero maximo "))

class FiboIter():

    
    def __init__(self, max_number:int):
        self.max_number = max_number
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            
            if self.aux >= self.max_number:
                raise StopIteration

            self.n1, self.n2 = self.n2, self.aux #swaping
            self.counter += 1
            return self.aux

        
        
if __name__ == '__main__':
    fibonacci = FiboIter(max_number)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)
import time

class iterator():

    def __init__(self, stop_number= None):
        
        self.max_number = stop_number
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.number = 0
        return self

    def __next__(self):
        
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.counter += 1
            self.number = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.number
            if not self.max_number or self.number <= self.max_number:
                return self.number
            else:
                raise StopIteration



if __name__ == '__main__':
    
    fibonacci = iterator(10)
    for i in fibonacci:
        print(i)
        time.sleep(1)

CODIGO:

class Fibonacci():
    def __init__(self, quantity):
        self.counter = quantity
        self.current = 0
        self.next = 1
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.counter == 0:
           raise StopIteration

        self.counter -= 1
        next = self.current + self.next
        self.current = self.next
        self.next = next
        self.index += 1
        return self.current

def run():
    fibonacci_10 = Fibonacci(10)
    order = 0
    for fibonacci in fibonacci_10:
        order += 1
        print(f'{order}: {fibonacci}')


if __name__ == "__main__":
    run() 

EJECUCION:

1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
10: 55
Process finished with exit code 0 
import time


class FiboIter():

    def __init__(self, max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            if not self.max or self.aux <= self.max:
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            else:
                raise StopIteration


def run():
    max = input("Ingrese un máximo: ")
    assert max == "" or (max.isnumeric() and int(
        max)) != 0, "Sólo se permiten enteros positivos, o presione enter para no ingresar un máximo"
    if max.isnumeric():
        max = int(max)
    fibonacci = FiboIter(max)
    for element in fibonacci:
        print(element)
        time.sleep(1)


if __name__ == '__main__':
    run()


Comparto

class FiboIter:
    def __init__(self, Max):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.Max = Max

    
    def __iter__(self):
        return self



    def  __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.counter <= self.Max:
            self.aux = self.n1 +self.n2
            self.n1,self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux
        else: 
            raise StopIteration        


fibonacci = FiboIter(50)   #Ingrese aquí has cuál termino de la sucesión de Fibinacci desea imprimir 
for element in fibonacci:
    print(element)

He hecho el código de la clase un poco más diferente, un poquito más simple.

#!/usr/bin/python3

class FibonacciSequence ():
    def __init__ (self, max_num: int=None):
        self.max: int = max_num

    def __iter__ (self):
        self.num_1: int = 0
        self.num_2: int = 1
        self.num_iterations: int = 0
        self.result_sum: int = 0
        return self

    def __next__ (self):
        self.num_iterations += 1

        if self.num_iterations == 1:
            return self.num_1
        elif self.num_iterations == 2:
            return self.num_2

        if not self.max or self.num_iterations <= self.max:
            self.result_sum = self.num_1 + self.num_2

            self.num_1, self.num_2 = self.num_2, self.result_sum
            return self.result_sum
        else:
            raise StopIteration


if __name__ == "__main__":
    fibonacci = FibonacciSequence(10)

    for num in fibonacci:
        print(num)





import time 

class FiboIter():
    max = int
    
    def __init__(self, max):
        self.max = max
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            # forma resumida de las 2 lineas de arriba usando swapping
            self.counter += 1
            if self.aux >= self.max:
                raise StopIteration
            else:
                return self.aux


if __name__ == '__main__':
    maximo =  int(input("Ingresa máximo numero de succesion de Fibonacci: "))
    assert type(maximo) == int, "Sólo puedes ingresar números enteros"
    fibonacci = FiboIter(maximo)
    
    for element in fibonacci:
        print(element)
        time.sleep(0.5)
import time

class FiboIter:

    def __init__(self, max:int=None):
        self.max = max
        self.n1 = 0
        self.n2 = 1
        self.counter = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            if self.max is not None and self.aux >= self.max:
                raise StopIteration
            return self.aux

            
if __name__ == '__main__':
    fibonacci = FiboIter(50)
    for i in fibonacci:
        print(i)
        time.sleep(0.5)
        if i > 100:
            break
import time

class Fibonacci_Iter():
    
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            if self.aux < self.max:
                return self.aux
            else:
                raise StopIteration

if __name__ == '__main__':
    fibonacci = Fibonacci_Iter

    for element in fibonacci(40):
        print(element)
        time.sleep(0.05)

Devuelve el numero de iteraciones que se elijan

import time

class Fibonacci_Iter():
    
    def __init__(self, max):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.counter < self.max:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux
        else:
            raise StopIteration

if __name__ == '__main__':
    fibonacci = Fibonacci_Iter

    for element in fibonacci(20):
        print(element)
        time.sleep(0.05)

Mi versión del reto saludos.

Agregué la condición de finalización dependiendo de una entrada por consola del numero máximo de términos que se desean. Saludos.

import time

class FiboIter:
    def __init__(self, max=None) -> None:
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter < self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                #self.n1 = self.n2
                #self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration

if __name__=='__main__':
    max = input("Ingresa el el número máximo de elementos de la serie que quieres...")
    fibonacci = FiboIter(int(max))
    for element in fibonacci:
        print (element)
        time.sleep(0.3)

Hola!
Solo agregué una función “init”, para definir el máximo y una sentencia “if” qué envuelve el código de fibonacci.

import time

class fiboiter():
    def __init__(self, max:int):
        self.max = max
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
    
    def __next__(self):
        if self.max >= self.n1 + self.n2:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2    
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration
        
if __name__ == '__main__':
    fibo = fiboiter(100)
    for elem in fibo:
        print(elem) 
        time.sleep(0.1)     
import time

class FiboIter():
    def __init__(self,max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter +=1
            return self.n2
        elif self.n2 >= self.max:
            raise StopIteration
        else:
            self.aux = self.n1 + self.n2
            self.n1,self.n2 = self.n2, self.aux
            self.counter +=1
            return self.aux
            if self.aux >= self.max:
                raise StopIteration

if __name__ == '__main__':
    fibonacci = FiboIter(int(input("Ingrese el numero maximo: ")))
    for element in fibonacci:
        print(element)
        time.sleep(1)

Reto elaborado

Hola, mi aporte intentando mantener las mejores prácticas posibles.

import time

class FiboIter():

    def __init__(self, max=None):
        self.max = max


    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self


    def __next__(self):
        if not self.max or self.counter < self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                #self.n1 = self.n2
                #self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration


if __name__ == '__main__':
    fibonacci = FiboIter(30)
    for element in fibonacci:
        print(element)
        time.sleep(0.5)

Mi aporte, funcionaría tanto si se define un máximo como si no:

import time

class FiboIter():

    def __init__(self, max_value = None):
        self.max_value = max_value

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            result = self.n1
        elif self.counter == 1:
            self.counter += 1
            result = self.n2
        else:
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            result = self.aux
        if self.max_value is not None:
            if result > self.max_value:
                raise StopIteration
        return result


if __name__ == "__main__":
    fibonacci = FiboIter(200)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)

Una buena práctica en general es evitar el uso de else ya que cuando se hacen returns quedan un poco sobrados

Acá les dejo mis mejoras:

import time


MAX_ITERATIONS = 10

class FiboIter(object):
    def __init__(self, max_iterations: int = MAX_ITERATIONS):
        self.max_iterations = max_iterations

    def __iter__(self) -> 'FiboIter':
        self.n1 = 0
        self.n2 = 1
        self.counter = 0

        return self

    def __next__(self) -> int:
        if self.counter >= self.max_iterations:
            raise StopIteration

        if self.counter == 0:
            self.counter += 1
            return self.n1

        if self.counter == 1:
            self.counter += 1
            return self.n2

        aux = self.n1 + self.n2
        self.n1, self.n2 = self.n2, aux
        self.counter += 1

        return aux


if __name__ == '__main__':
    fibonacci = FiboIter()

    for element in fibonacci:
        print(element)
        time.sleep(0.05)
class Fibonacci:
    """
    Class that implements an iterator of all elements in
    Fibonacci's susession.
    """
    def __init__(self, n=None) -> None:
        self.n = n
        self.counter = 0

    def __iter__(self):
        self.num1 = 0
        self.num2 = 1
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter +=1
            return self.num1
        elif self.counter == 1:
            self.counter +=1
            return self.num2
        elif not self.n or self.counter < self.n:
            result = self.num1 + self.num2
            self.num1,  self.num2 = self.num2, result
            self.counter += 1
            return result
        else:
            raise StopIteration

for i in Fibonacci(13):
    print(i)

Acá está mi código para el reto:

class Fibonacci:
    """
    Class that implements an iterator of all elements in
    Fibonacci's susession.
    """
    def __init__(self, n=None) -> None:
        self.n = n
        self.counter = 0

    def __iter__(self):
        self.num1 = 0
        self.num2 = 1
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter +=1
            return self.num1
        elif self.counter == 1:
            self.counter +=1
            return self.num2
        elif not self.n or self.counter < self.n:
            result = self.num1 + self.num2
            self.num1,  self.num2 = self.num2, result
            self.counter += 1
            return result
        else:
            raise StopIteration

for i in Fibonacci(13):
    print(i)
"""Este programa lo que hace es poner a prueba la conjetura de collatz,
disclaimer: El programa era un intento de hacer algo diferente, pero no logre que funcionara, solo imprime la secuencia final es decir 1 de forma periódica. pero seria un buen ejercicio ayudarme a hacerlo funcionar
"""

# se toma un integer positivo n
# se divide por 2
# si el numero que regresa es par se vuelve a dividir por 2
# si el numeor que regresa es impar se aplica 3*n + 1
# esto se hace en un ciclo

import time 

class CollatzIter():
    
    def __iter__(self):
        self.n = int(input("Ingresa un numero positivo: "))
        return self
    
    def __next__(self):
        num_seq = [self.n]
        if self.n < 1:
            print("el numero debe ser positivo")
        while self.n > 1:
            if self.n % 2 == 0:
                self.n = self.n / 2
            else:
                self.n = 3 * self.n  + 1
        return self.n

if __name__ == '__main__':
    collatz = CollatzIter()
    for element in collatz:
        print(element)
        time.sleep(0.5) 

El reto:

from time import sleep

class Fibonacci():
    def __init__(self):
        self.max = int(input("Ingrese el numero máximo de iteración :"))
  
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self


    def __next__(self):
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            elif self.counter <= self.max:
                self.aux = self.n1 + self.n2
                self.n1,self.n2 = self.n2,self.aux
                self.counter +=1
                return self.aux
            else:
                raise StopIteration
             

if __name__ == '__main__':
    fibo = Fibonacci()
    for element in fibo:
        print(element)
        sleep(0.1)

No será la mejor solución pero funciona:

import time

class FiboIter():

    def __init__(self, max_number: int):
        self.max_number = max_number

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.aux = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter +=1
            return self.n2
        else:
            if (self.aux+self.n2) < self.max_number:
                self.aux = self.n1 + self.n2
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter+=1
                return self.aux
            else:
                raise StopIteration

if __name__ == "__main__":
    fibonacci = FiboIter(70)
    for element in fibonacci:
        print(element)
        time.sleep(1)

Swap

El siguiente código es si deseas preguntarle al usuario cual es el valor máximo permitido, por lo que el programa se ejecutara hasta el valor menor inmediato y hará una impresión del valor siguiente que es mayor al valor máximo (que no está incluido en la impresión)

from time import sleep

class FiboIter():
    
    def __init__(self, max_number: int):
        self.max_number = max_number
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.aux = 0
        return self
    
    def __next__(self):
        if self.max_number == 0:
            print(self.n1)
            print(f'El proximo valor de la sucesión es: {self.n2} el cual es mayor al valor maximo permitido ({self.max_number})')
            raise StopIteration
        elif self.max_number == 1:
            print(self.n1)
            print(self.n2)
            print(self.n2)
            print(f'El proximo valor de la sucesión es: {self.n2 + self.n2} el cual es mayor al valor maximo permitido ({self.max_number})')
            raise StopIteration
        elif self.aux <= self.max_number:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                if self.aux > self.max_number:
                    print(f'El proximo valor de la sucesión es: {self.aux} el cual es mayor al valor maximo permitido ({self.max_number})')
                    raise StopIteration
                return self.aux

if __name__ == '__main__':
    max_number = int(input('Introduce el valor maximo deseado de la sucesión de Fibonacci: '))
    fibonacci = FiboIter(max_number)
    
    for element in fibonacci:
        print(element)
        sleep(0.05)

Al momento de escribir el código tuve un problema cuando el valor pasado era 0 o 1 por lo que decidí corregirlo con esos prints directos (No conseguí otra manera de corregirlo). Espero recomendaciones

import time


class FiboIter():

    def __init__(self, num_max=int):
        self.num_max = num_max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            if self.aux < self.num_max:                
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            else:
                print(f"el numero mayor mas cercano es {self.aux}")
                raise StopIteration
            
                


if __name__ == "__main__":
    num = int(input("escribe el numero tope: "))
    
    print(f"Elegiste {num}, veamos cual es el numero fibo que mas se acerca a tu elección...")

    fibonacci = FiboIter(num)
    for element in fibonacci:
        print(element)
        time.sleep(.1)
    print(f"el numero menor mas cercano es {element}")

Reto superado. No es mucho pero es trabajo honrado 😄 No sabía que ya sabía bastante de Python. Esto sí es un logro personal muy importante!

import time

class FiboIter():
    
    def __init__(self, maximo):
        self.maximo = maximo

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.n2 < maximo:
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            if self.n2 >= maximo:
                raise StopIteration
            return self.aux

if __name__ == '__main__':
    maximo = int(input("Inserta el número máximo para secuencia de FIbonacci: "))
    print(f'Estos son todos los número que hay entre 0 y {maximo} de la secuencia de Fibonacci:')
    fibonacci = FiboIter(maximo)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)

Mi solución:

import time

class FiboIter():

    def __init__(self, max_number):
        self.max_number = max_number

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        self.aux = self.n1 + self.n2

        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            if self.aux <= self.max_number:
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            else:
                raise StopIteration

if __name__ == "__main__":
    max_number = int(input('Escribe un máximo a llegar: '))

    while max_number == 0:
        max_number = int(input('Escribe un número diferente a cero: '))

    fibonacci = FiboIter(max_number)

    for element in fibonacci:
        print(element)
        time.sleep(0.05)

    print('fin de la sesión.')

A la antigua 😀

import time


class FiboIter():

    def __init__(self, max=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max or self.counter < self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter += 1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                # self.n1 = self.n2
                # self.n2 = self.aux
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration


if __name__ == '__main__':

    while True:
        try:
            max_itter = int(
                input("Ingrese la cantidad de números de la succesion   que  desea ver:  "))
 
            break

        except ValueError:
            print("Error, Recuerde que debe ingresar números enteros")

    fibonaci = FiboIter(max_itter)

    for element in fibonaci:
        print(element)
        time.sleep(1)


le agrege que el usuario digitara el valor y que este fuera validado

Una gran practica, me imagino las cosas que se pueden hacer con los iteradores

import time

maximo = int(input("Numero maximo: "))


class FiboIter():
    def __init__(self, max=maximo) -> None:
        self.max = max
        return None

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            if not self.max or self.aux <= self.max:
                # SWAP two elements in a list
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
            else:
                raise StopIteration


if __name__ == '__main__':
    # Instance
    fibonacci = FiboIter()
    for element in fibonacci:
        print(element)
        time.sleep(1)

ok, mi solución, aquí entrego los numeros de fibonacci que el usuario ponga al crear el objeto:

import time

class FiboIter:
    
    def __init__(self, stop: int) -> None:
        self.stop = stop

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
        
    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter ==1:
            self.counter +=1
            return self.n2
        elif self.counter > self.stop - 1:
            raise StopIteration   
        else:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter +=1
            return self.aux



if __name__ == '__main__':
    fibonacci = FiboIter(10)
    for element in fibonacci:
        print(element)
        time.sleep(0.05)

Mi aporte al reto!!:

import time 

class FiboIter():

    def __init__(self, max = None):
        self.max = max
        
    def __iter__(self): 
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1 
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux 
            self.counter += 1
            
            if self.max == None:
                return self.aux
            
            elif self.counter <= self.max:
                return self.aux
            
            else:
                raise StopIteration

        
if __name__ == '__main__':
    fibonacci = FiboIter()
    for element in fibonacci:
        print(element)
        time.sleep(1) 

Contiene también un valor por defecto para max, en caso de que no pongan un valor max

Reto Solucionado!!!

Reto: Fibonacci con iteracion limitada

import time

class fiboIter():
    
    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self
    
    def __next__(self, ):
     
        if self.counter == 0:
            self.counter += 1
            return self.n1
     
        if self.counter == 1:
            self.counter += 1
            return self.n2

        elif self.counter <= 8:                            # LIMITED ITERATION
            self.aux = self.n1 + self.n2
            self.n1, self.n2 = self.n2, self.aux              # swapping
            self.counter += 1
            return self.aux

        else:                                               # STOP ITERATION
            raise StopIteration

if __name__ == "__main__":
    fibonacci = fiboIter()
    for element in fibonacci:
        print(element)
        time.sleep(1)

Algo que no vi en los aportes fue que el maximo se pudiera ingresar por consola, por eso me tome el tiempo de hacerlo yo:

import time


class FiboIter:

    def __init__(self, max = None):
        self.max = max


    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter ==1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            self.counter += 1
            self.n1, self.n2 = self.n2, self.aux
            if not self.max:
                return self.aux

            if self.max:
                if self.aux > self.max:
                    raise StopIteration
                else:
                    return self.aux


def main():
    max = int(input('Enter a maximum number: ') or 0)
    fibonacci = FiboIter(max)
    for i in fibonacci:
        print(i)
        time.sleep(0.05)


if __name__ == '__main__':
    main()
import time

class FiboIter():

    def __init__(self, max: int) -> None:
        self.max = max
        self.aux = 0


    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self


    def __next__(self):
        if not self.max or self.aux <= self.max:

            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter +=1
                return self.n2
            else:
                self.aux = self.n1 + self.n2

                # Swapping, el mismo código pero en una sola línea
                self.n1, self.n2 = self.n2, self.aux
                self.counter +=1
                return self.aux
                
        else:
            raise StopIteration


if __name__ == "__main__":
    fibonacci = FiboIter(20)    # Aquí se ejecuta __init__() y __iter__()
    for element in fibonacci:   # En el ciclo for se ejecuta el método __next__()
        print(element)
        time.sleep(1)

Usando type hints y la nueva feature de Python 3.10, el esperado match-case.

Estimados compañeros, es de mi agrado informarles que resolví el reto de la siguiente manera:

•Agregué un input para que el usuario defina el limite
•Luego procedo a definir un atributo limit que es igual al límite definido y recibido como argumento en iter.
•Elevo una excepción StopIteration cuando el contador es igual a el límite definido.

import time
class FiboIter():
    userlimit = int(input("Ingrese el limite de iteraciones: "))
    def __iter__(self, limit = userlimit ):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        self.limit = limit
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        elif self.counter == self.limit:
            raise StopIteration
        else:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux

if __name__ == '__main__':
    fibonacci = FiboIter()
    for element in fibonacci:
            print(element)
            time.sleep(0.05)

#Una solución alternativa podría ser romper el ciclo usando break, cuando se obtenga un resultado de la secuencia determinado por el usuario al crear el loop for de la siguiente manera:

import time
class FiboIter():

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if self.counter == 0:
            self.counter += 1
            return self.n1
        elif self.counter == 1:
            self.counter += 1
            return self.n2
        else:
            self.aux = self.n1 + self.n2
            # self.n1 = self.n2
            # self.n2 = self.aux
            self.n1, self.n2 = self.n2, self.aux
            self.counter += 1
            return self.aux

if __name__ == '__main__':

    fibonacci = FiboIter()
    userlimit = int(input("Ingrese el valor limite de la secuencia: "))
    for element in fibonacci:
        if element > userlimit:
            break
        else:
            print(element)
            time.sleep(0.05)

Hola a todos.

Comparto la solución al reto del profe Facundo:

import time

class FiboIter:
    def __init__(self, max : int = None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__(self):
        if not self.max or self.counter <= self.max:
            if self.counter == 0:
                self.counter += 1
                return self.n1
            elif self.counter == 1:
                self.counter +=1
                return self.n2
            else:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux
        else:
            raise StopIteration

if __name__ == '__main__':
    fibonacci = FiboIter(100)
    for i in fibonacci:
        print(i)
        time.sleep(0.5)

from time import sleep
class FiboIter():

def __init__(self, max_number:int):
    self.max_number = max_number

def __iter__(self):
    self.n1 = 0
    self.n2 = 1
    self.counter = 0
    return self

def __next__(self):

    if self.counter == 0:
        self.counter += 1
        return self.n1
    elif self.counter == 1:
        self.counter += 1
        return self.n2
    else:
        self.aux = self.n1 + self.n2
        
        if self.aux >= self.max_number:
            raise StopIteration
        
        self.n1, self.n2 = self.n2, self.aux
        self.counter += 1
        return self.aux

if name == “main”:
for element in FiboIter(39):
print(element)
sleep(0.1)

Esta es mi solución, simple y eficaz 😃
Cualquier feedback estaría enormemente agradecido.

import time

class FiboIter():

    def __init__(self, max:int=None):
        self.max = max

    def __iter__(self):
        self.n1 = 0
        self.n2 = 1
        self.counter = 0
        return self

    def __next__ (self):
        if self.counter >= self.max:
            raise StopIteration
        else:
            if self.counter == 0:
                self.counter += 1
                return self.n1, self.counter
            elif self.counter == 1:
                self.counter += 1
                return self.n2, self.counter
            else:
                self.aux = self.n1 + self.n2
                self.n1, self.n2 = self.n2, self.aux
                self.counter += 1
                return self.aux, self.counter


if __name__ == "__main__":
    fibonacci = FiboIter

    for element in fibonacci(50):
        print(element)
        time.sleep(0.01)