Python Forum
prime numbers with iterator and generator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
prime numbers with iterator and generator
#7
(Dec-13-2022, 07:00 PM)deanhystad Wrote:
(Dec-13-2022, 06:06 PM)cametan_001 Wrote: This seems a sort of pit fall; thus I would watch out when I use a generator.
When you do this:
stream = filter(lambda x: x % head != 0, stream)
Python creates a closure that contains the variable "head" and the anonymous function generated by the lambda expression.
def anoinymous(x):
    return x % head != 0
When the lambda expression is in your iterator, the variable "head" is different for each closure because each call to __next__(self) creates a new "head" variable.

When the lambda expression is in your generator, the variable "head" is the same for each closure because you never leave the generator scope.

You should probably use this notation for your iterator to prevent having to create a closure for each lambda.
stream = filter(lambda x, y=head: x % y != 0, stream)
This creates an anonymous function that kind of looks like this:
def anonymous(x, y=2):
    return x % y != 0
No need now for a closure because we don't use any variables, only function arguments.

Thanks for the detailed explanation!
I tried some experiments like making a local function:

def anoinymous(x):
            nonlocal head
            return x % head != 0
, put it in the filter, and saw what is going on; however, as a result, what you showed is the only way to be succeess.

Anyway, thank you very much!
Reply


Messages In This Thread
RE: prime numbers with iterator and generator - by cametan_001 - Dec-14-2022, 02:00 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Prime numbers saima 1 553 Dec-09-2024, 02:19 AM
Last Post: jefsummers
  Why not use len(alist) in an iterator? Pedroski55 5 1,474 Jun-27-2024, 02:49 PM
Last Post: snippsat
  prime numbers astral_travel 28 8,550 Nov-08-2022, 09:23 PM
Last Post: astral_travel
  resetting an iterator to full Skaperen 7 11,360 Feb-20-2022, 11:11 PM
Last Post: Skaperen
  popping an iterator Skaperen 11 5,704 Oct-03-2021, 05:08 PM
Last Post: Skaperen
  q re glob.iglob iterator and close jimr 2 3,260 Aug-23-2021, 10:14 PM
Last Post: perfringo
  Problem with an iterator grimm1111 9 6,147 Feb-06-2021, 09:22 PM
Last Post: grimm1111
  Multi-class iterator Pedroski55 2 3,114 Jan-02-2021, 12:29 AM
Last Post: Pedroski55
  Return prime numbers from range krzyfigh 2 2,788 Apr-20-2020, 08:08 PM
Last Post: krzyfigh
  Generator function for even numbers mp3909 4 7,717 Mar-21-2020, 07:40 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020