Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

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

1 Answer 1

up vote 3 down vote accepted

What about this?

[1] * one + result + [n] * itself
share|improve this answer
    
I was thinking [1]*int(one) + result + [n]*int(itself), scrolled down and saw this beauty. Didn't know this could be done. +1 –  S Prasanth Dec 13 '12 at 5:37
    
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. –  raylu Dec 14 '12 at 4:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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