Issue
Can I write this code in one line? I tried use chain in list comprehension.
def divisors(n):
result = []
for div in range(1, int(sqrt(n)) + 1):
if n % div == 0:
result.extend([div, n / div])
return list(set(result))
Solution
A set comprehension seems appropriate. Please also note that I've used //
rather than /
as floating point numbers are not relevant to this problem.
from math import sqrt
def divisors(n):
return {x for div in range(1, int(sqrt(n)) + 1)
if not (n % div)
for x in [div, n // div] }
divisors(15)
# {1, 3, 5, 15}
If you really wish to have a list, it's easy enough to turn the set into a list.
list(divisors(15))
# [1, 3, 5, 15]
Answered By - Chris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.