How do you use the generators?



  • I wrote a generator of simple numbers:

    def primes():
        prime = True
        i = 1
        while True:
            i += 1
            for j in range(2, i):
                if i % j == 0:
                    prime = False
            if prime:
                yield i
            else:
                prime = True
    

    But I don't know how to use it. I'm doing as a challenge:

    x = primes()
    print(x)
    

    The object is being released, not the number.

    In case of such a challenge print(next(primes())) All the time on the way out, I get 2.

    Right. Use generators?



  • def primes():
        prime = True
        i = 1
        while True:
            i += 1
            for j in range(2, i):
                if i % j == 0:
                    prime = False
            if prime:
                yield i
            else:
                prime = True
    

    No more than 100 simple numbers
    http://ideone.com/wiVXOE

    for p in primes():
    
    if p > 100:
        break
    print(p)
    

    Take out the first seven simple numbers:
    http://ideone.com/sYrLpA

    p = primes()

    for i in range(7):
    print(next(p))




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2