Reputation: 21781
I have started to write some Python code. What I have is:
from math import *
def ex(N):
l = []
sum = 0
N = abs(int(N));
for n in range(1,N):
if N % n == 0:
l.append(n)
sum += n
l.append(N)
print ' of '+str(N),l
print 'SUM', (sum+N)
I don't know if this is good or bad, but it is what I have tried :)
Is it possible to replicate the behavior of my code with list comprehension? If so, how?
Upvotes: 0
Views: 2236
Reputation: 852
You can use list comprehension to replace:
for n in range(1,N):
if N % n == 0:
l.append(n)
with:
[l.append(n) for n in range(1,N) if N % n == 0]
Whether it is good or bad, in this case, I'm not sure. I like to use them when I can, but for more complex cases sometimes I opt for the for
loop for readability.
Edit: Sorry, maybe I should have given a complete example.
def ex(N):
l = []
N = abs(int(N));
[l.append(n) for n in range(1,N) if N % n == 0]
l.append(N)
print l
print sum(l)
Upvotes: 0
Reputation: 44351
Very simply (this actually uses a generator expression rather than a list comprehension, if you don't need to keep the results).
def ex(N):
N = abs(int(N))
print 'SUM', sum(n for n in xrange(1, N + 1) if N % n == 0)
If you care about the list, then instead:
def ex2(N):
N = abs(int(N))
l = [n for n in xrange(1, N + 1) if N % n == 0]
print ' of '+str(N),l
print 'SUM', sum(l)
You might find the Dive Into Python 3 explanation of list comprehensions useful, or if you've got some free hours, try watching an introductory Python tutorial.
Upvotes: 5
Reputation: 6855
You can do it with list-comprehension:
def ex(N):
N = abs(int(N))
l = [n for n in range(1, N + 1) if N % n == 0]
print ' of '+str(N),l
print sum(l)
You will keep the n for each n in the range from 1 to N(inclusive) if the condition(N % n == 0) is true. You will keep the list in l and then the function sum calculates the sum of the list.
Whether it is good or bad using list comprehension is up to you, but it is usually used as it is efficient and compact. And if you don't need a list because you just need to use the values one after the other and only one time generators
are recommended because they don't use memory.
Upvotes: 4