0

I'm trying to learn send method for generators but i'm confused about its functionality. Below is the code . I want to understand why do we need to initialize generator by passing 'None' value or using next method (print_successive_primes)--Both give same result? But if i normally use generator (in case solve_number_10) i just simply pass argument and generator initializes itself.

i've read this answer here python generator "send" function purpose?

but it doesn't clear my doubt

import math
def is_prime(number):
    if number > 1:
        if number == 2:
            return True
        if number % 2 == 0:
            return False
        for current in range(3, int(math.sqrt(number) + 1), 2):
            if number % current == 0: 
                return False
        return True
    return False


def get_primes():
    number = yield
    #print(number)
    while True:
        if is_prime(number):
            number = yield number
        number += 1

def print_successive_primes(iterations, base=10):
    prime_generator = get_primes()
    #print(next(prime_generator))
    print(prime_generator.send(None))
    #print(prime_generator.send(12))
    for power in range(iterations):
        print(prime_generator.send(base ** power))

print_successive_primes(4)

####
def solve_number_10():
    # She *is* working on Project Euler #10, I knew it!
    total = 2
    for next_prime in get_primes(3):
        if next_prime < 800000:
            total += next_prime
        else:
            print(total)
            return

Jeet Singh
  • 303
  • 1
  • 2
  • 10
  • The question you linked to has a pretty good answer already, and there is no point to write it again here. What exactly you did not understand? The `send` method is used to *input* a value into the generator – DeepSpace Mar 26 '19 at 09:02
  • i've written above..why do we need to "initialize" a generator while using send method? why can't i simply omit this statement 'prime_generator.send(None)' and directly use for loop. it give me error-- non-None value can not be passed. Why first yield doesn't initialize on it's own like in other case? – Jeet Singh Mar 26 '19 at 09:10
  • @JeetSingh: Hope you're aware that the value that is passed through `send()` becomes the value of the `yield` expression inside the generator function. Armed with this basic knowledge, I found this answer helpful https://stackoverflow.com/a/19892334/8561957 to understand why we need to pass `None` – fountainhead Mar 26 '19 at 09:44
  • I also found this answer helpful https://stackoverflow.com/a/51867447/8561957. In fact, I suggest you read this first, before you read the earlier one I pointed to above. – fountainhead Mar 26 '19 at 09:49
  • @fountainhead Thank You so much!! That link was really helpful! – Jeet Singh Mar 26 '19 at 12:59

0 Answers0