Home > Enterprise >  i don't understand this lambda
i don't understand this lambda

Time:01-15

i looked on the web for a lambda that one could use to get prime numbers. i found this:

nums = range(2, 100)
for i in range(2, 10):
    nums = list(filter(lambda x: x == i or x % i, nums))
print(nums)

i understand how x % i —being i a list of numbers from 2 to 10— can filter out the non-prime numbers that are higher then 10; what boggles my mind is how would one add the i list to the final nums.

i believe it may have something to do with the x == i boolean but i can't understand how it works.

CodePudding user response:

Lambda-Functions can be used to shorten code. They can be compared to "normal" functions which use at least two lines of code. func will be the same as your lambda-function:

def func(x):
    return x == i or x % i

Driver Code:

nums = range(2, 100)
nums_a = []
for i in range(2, 10):
    nums = list(filter(lambda x: x == i or x % i, nums))
    nums_a = list(filter(func, nums))

print(nums_a)
print(nums)

CodePudding user response:

This lambda function wants to check if a number is equal to a number between 2 and 9 and is not divisible by any one of them.

In other words, the whole program what to filter the prime numbers here the list is from 2 to 99 the in the loop. we just need to check the divisors from 2 to 9 because If we pass to 10 we could find 10 * 10 = 100.

  • Related