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?

  • \$\begingroup\$ The straight forward way isn't that verbose. I don't see a different way to do it the doesn't sacrifice readability. \$\endgroup\$ – unholysampler Dec 12 '12 at 3:46
  • \$\begingroup\$ You may think it is verbose but it is self explanatory and can easily be commented out without messing around with the core code. \$\endgroup\$ – Apprentice Queue Dec 12 '12 at 4:34

What about this?

[1] * one + result + [n] * itself
  • 1
    \$\begingroup\$ I was thinking [1]*int(one) + result + [n]*int(itself), scrolled down and saw this beauty. Didn't know this could be done. +1 \$\endgroup\$ – Prasanth S Dec 13 '12 at 5:37
  • \$\begingroup\$ interesting... but please don't actually do this. "Programs must be written for people to read and only incidentally for machines to execute." This takes me way longer to read than the 4-liner. \$\endgroup\$ – raylu Dec 14 '12 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.