0

I want to create a set of values that can divide a specific number. In my code below, I want factors of number 12.

x=12
a=set(map(lambda i:i if(x%i==0),range(1,x+1)))
print(a)

I expected output to be {1,2,3,4,6,12}.

but i have got some error:

  File "<ipython-input-18-7f73bd4c5148>", line 2
    a=set(map(lambda i:i if(x%i==0),range(1,x+1)))
                                   ^
SyntaxError: invalid syntax

sai kiran
  • 11
  • 3
  • I think your lambda is supposed to be `lambda i : x%i==0`. What you have now doesn't make sense. And I think you should be using `filter` instead of `map`. – khelwood Oct 22 '19 at 13:41

4 Answers4

2

I think your lambda is supposed to be lambda i : x%i==0. What you have now doesn't make sense. And I think you should be using filter instead of map.

>>> x = 12
>>> a = set(filter(lambda i:x%i==0, range(1,x+1)))
>>> print(a)
{1, 2, 3, 4, 6, 12}
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

Looks like you are confusing lambda notation with list/set comprehension notation. The correct way using lambda and filter (not map) has already been shown, so here's a version using a set comprehension:

>>> x = 12
>>> {i for i in range(1, x+1) if x % i == 0}
{1, 2, 3, 4, 6, 12}

As you see, the i if ... is present here (although distributed over different parts of the expression), but not in the lambda.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

try a=set(filter(lambda i: True if(x%i==0) else False,range(1,x+1)))

The condition in lambda function should be defined as explained here: Conditional statement in a one line lambda function in python?

0

I would recommend using a generator or function instead of a lambda as they are not PEP-8 compliant and typically make logic more complex. Using a generator will also allow you to save memory if you are going to be making very long sequences.

Example generator

gen = (x for x in range(1, 1000000000) if 12 % x == 0)
CMMCD
  • 360
  • 1
  • 8