pythonic. python , , , -.
, . . , . , . , . .
, , , .
k=1000
def transform(input):
return input + 1
"""
1. range(k) allocates a k element list [0...k]
2. Iterate over each element in that list and compute the transform
3. Store the results in a list
4. Pass the list to sum
Memory: Allocates enough 2 lists of size k
"""
print sum([transform(i) for i in range(k)])
"""
1. Create an xrange object
2. Pass transform and xrange object to map
3. Map returns a list of results [1...k+1]
4. Pass list to sum
Memory: Creates a constant size object and creates a list of size k
"""
print sum(map(transform, xrange(k)))
"""
1. Create an xrange object
2. Create a generator object
3. Pass generator object to sum
Memory: Allocates 2 objects of constant size
"""
print sum(transform(i) for i in xrange(k))
"""
Create a generator object and operate on it directly
"""
g = (transform(i) for i in xrange(k))
print dir(g)
print g.next()
print g.next()
print g.next()