I have a function for finding factors of a number in Python
def factors(n, one=True, itself=False):
def factors_functional():
# factors below sqrt(n)
a = filter(lambda x: n % x == 0,
xrange(2, int(n**0.5)+1))
result = a + map(lambda x: n / x, reversed(a))
return result
factors(28)
gives [2, 4, 7, 14]
. Now i want this function to also include 1 in the beginning of a list, if one
is true, and 28 in the end, if itself
is true.
([1] if one else []) + a + map(lambda x: n / x, reversed(a)) + ([n] if itself else [])
This is "clever" but inelegant.
if one:
result = [1] + result
if itself:
result = result + [n]
This is straight-forward but verbose.
Is it possible to implement optional one and itself in the output with the most concise yet readable code possible? Or maybe the whole idea should be done some other way - like the function factors
can be written differently and still add optional 1 and itself?