maharaja
maharaja

Reputation: 13

How can I reduce the following code in single line 'for' loop

I have following code.

for i in range(1,number):
    if (number%i) == 0:
        divisorSum += i   

How can I reduce this code in just one line in python

Upvotes: 1

Views: 87

Answers (2)

ssm
ssm

Reputation: 5373

You can try using filter:

sum( filter(lambda i: not number % i, range(1,7)) )

Note that in Python, 0 is False. So not 0 is True. not number % i Checks for your stipulated condition. sum does the addition that you do iteratively.

Upvotes: 1

NPE
NPE

Reputation: 500327

Here is one way:

divisorSum += sum(i for i in range(1, number) if number % i == 0)

Whether this is more, or less, readable than the original is in the eye of the beholder.

I've used += to keep the code exactly equivalent to yours. If you initialize divisorSum to zero before the loop, you can replace += with = and get rid of the initialization.

Finally, it's worth noting that your code only computes proper divisors. If you do need to include the number itself, use range(1, number + 1).

Upvotes: 6

Related Questions