Home > other >  [Python] [question] about the lambda function
[Python] [question] about the lambda function

Time:02-17

New small white, recently in a Python implementation sieve method prime Numbers and encounter a strange situation:
 def odd () : # generate an infinite odd number sequence 
N=1
While 1:
Yield 2 * n + 1
N +=1

Def nd (n) : # screening function
Return the lambda x: x % n> 0

Def prime (seq) :
Yield 2
While 1:
P=next (seq)
Yield (p)
Seq=filter (nd (p), seq) # screen method to update the prime sequence

Oseq=odd ()
Pr=prime (oseq)
Print ([next (pr) for I in range (100)])


The correct output:
 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541] 


Screening function contains only one lambda expressions, but if you don't define filter function, directly on the screen when using lambda expressions, can appear wrong results (output all the odd number) :

 def odd () : # generate an infinite odd number sequence 
N=1
While 1:
Yield 2 * n + 1
N +=1

Def prime (seq) :
Yield 2
While 1:
P=next (seq)
Yield (p)
Seq=filter (lambda x: x % p> # 0, seq) screening method to update the prime sequence

Oseq=odd ()
Pr=prime (oseq)
Print ([next (pr) for I in range (100)])


Output:
 [2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101, 103, 105, 107, 109, 111, 113, 115, 117, 119, 121, 123, 125, 127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189, 191, 193, 195, 197, 199] 


In the attempt to the nature of the lambda + filter also appeared strange results:


For each great god answered... Thank you very much!
  • Related