3
\$\begingroup\$

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?

\$\endgroup\$
2
  • \$\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\$ Commented Dec 12, 2012 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\$ Commented Dec 12, 2012 at 4:34

1 Answer 1

5
\$\begingroup\$

What about this?

[1] * one + result + [n] * itself
\$\endgroup\$
2
  • 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
    Commented Dec 13, 2012 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
    Commented Dec 14, 2012 at 4:47

Your Answer

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

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