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

1
  • 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. Commented Oct 22, 2019 at 13:41

4 Answers 4

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}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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?

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.