3

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))
Ashtart
  • 121
  • 5

3 Answers3

6

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]
Chris
  • 26,361
  • 5
  • 21
  • 42
2

Are you looking for something like this ?

from math import sqrt
import itertools

def divisors(n):
    return list(set(itertools.chain.from_iterable([[div, n / div] for div in range(1, int(sqrt(n)) + 1) if n % div == 0])))
Amish Gupta
  • 139
  • 8
joaopfg
  • 1,227
  • 2
  • 9
  • 18
  • At least one level of this is unnecessary. `list(set(list(itertools...` vs. `list(set(itertools...` – Chris Aug 19 '22 at 20:03
  • You also don't need to pass a list to `from_iterable`. You can pass a generator expression. `list(set(itertools.chain.from_iterable([div, n / div] for div in range(1, int(sqrt(n)) + 1) if n % div == 0)))`. Having said that, these are relatively minor issues. Ultimately this is a very un-Pythonic approach to solving this problem: passing on the obvious solution in favor of a "clever" approach that is comparatively difficult to decipher. – Chris Aug 20 '22 at 07:05
  • @Chris Thanks for suggestion. My goal was to get the same outputs as the OP's function. I believe this function achieve this goal although not very pythonic. The other solutions here all return an ordered output with all elements as integers. Maybe the OP needed the output like that for some particular reason. I think you should ask him first instead of making suppositions. Anyway, your solution is nice. – joaopfg Aug 20 '22 at 09:46
1

refer the link: list.extend and list comprehension

def divisors(n):
    return list({i for div in range(1, int((n)**0.5) + 1) for i in [div, n // div] if n % div == 0})

sample input:

print(divisors(30))

Output

[1, 2, 3, 5, 6, 10, 15, 30]
Chris
  • 26,361
  • 5
  • 21
  • 42
Amish Gupta
  • 139
  • 8