#Example; Building Python lists.
import timeit
#Build a list consisting of ten elements using the append method.
def build_append():
list_obj=[]
for i in range(0,10):
list_obj.append(i)
#Build a list consisting of ten elements using the inline method.
def build_inline():
list_obj=[i for i in range(0,10)]
if __name__=="__main__":
#Setup timers.
t_append=timeit.Timer("build_append()",\
"from __main__ import build_append")
t_inline=timeit.Timer("build_inline()",\
"from __main__ import build_inline")
#Execute timers.
r_append=t_append.timeit()
r_inline=t_inline.timeit()
#Show results.
print "APPEND:",r_append
print "INLINE:",r_inline
print "DIFF %:",(r_inline/r_append)*100
Showing posts with label iteration. Show all posts
Showing posts with label iteration. Show all posts
Thursday, August 27, 2009
Building Python Lists
Building primitive Python lists is a common task in virtually any Python application. The Python list is not unlike a traditional array in many respects, only more powerful. A common scenario is building a Python list from an iterator that yields values. In this case, each iteration adds a new element to the list being built. One method used to build Python lists using an iteration construct is the append method. This approach invokes the list append() method to append a new list element. Another approach to building Python lists is to place the iteration itself within the new list. This approach can be considered inline list building. The benefit to using the inline approach is the performance gain. The benefit to using the append method is readability when logic is required within each iteration that appends elements to the list. Below is an example illustrating both approaches.
Wednesday, August 5, 2009
jQuery each
Performing iteration activities in javascript is actually slightly more complicated a task than it should be. This is brought about by the cross-browser inconsistencies. Developers can't implement standard javascript looping constructs and expect them to work the same way across multiple browsers. This is simply the reality of web application development. The other reality is that if any developer expects to be productive, they will use a javascript toolkit such as jQuery. Thankfully, the jQuery.each() function provides a cross-browser iteration facility. All the developer needs to supply is the sequence to be iterated over and the callback for each element in the sequence. In addition to the cross-browser iteration support, the jQuery.each() function provides flexibility in javascript applications. The function can accept both arrays and objects as the sequence to iterate over.
Here is an example illustrating the jQuery.each() function iterating over an array.
Also, during iterations, there will more often than not be a need to terminate the loop. This is achieved by returning false from the iteration callback as is illustrated below.
Here is an example illustrating the jQuery.each() function iterating over an array.
//Example; jQuery.each()
var arr=["One", "Two", "Three"];
jQuery(arr).each(function(){
console.log(this);
});
//Example; jQuery.each()
var arr=["One", "Two", "Three"];
jQuery(arr).each(function(){
console.log(this);
if(this=="Two"){
return false;
}
});
Saturday, February 14, 2009
Custom Python iterators.
I've been experimenting with writing custom Python iterators. In Python, any sequence type can be iterated over. For example, when you say "for i in list_obj", list_obj actually returns an iterator. For this common case, the developer need not be concerned with the iterator. They know that it will always behave correctly in a for loop.
If you have a class that needs to be iterated over, you can define a custom iterator for your class as demonstrated below.
Here, we have a custom iterator defined, MyIterator. The constructor initializes the object it will iterate over as well as the counter. The __iter__() method is required to return the current MyIterator instance so the iterator can also be iterated over. Sort of like meta-iteration.
The important method is next() which returns the next item in the iteration. In this case, every time next() is invoked, we attempt to return the value of get() and increment the counter. Once there are no more items, we raise a StopIteration exception, which will gracefully exit the iteration.
Finally, you'll notice that MyClass defines a __iter__() method. This is what gives instances of MyClass that ability to be iterated over. The method simply returns a MyIterator instance.
If you have a class that needs to be iterated over, you can define a custom iterator for your class as demonstrated below.
#Example; Custom iterators.
class MyIterator:
def __init__(self, obj):
self.obj=obj
self.cnt=0
def __iter__(self):
return self
def next(self):
try:
result=self.obj.get(self.cnt)
self.cnt+=1
return result
except IndexError:
raise StopIteration
class MyClass:
def __init__(self):
self.data=["Item 1", "Item 2", "Item 3"]
def __iter__(self):
return MyIterator(self)
def get(self, index):
print "Getting item..."
return self.data[index]
if __name__=="__main__":
for item in MyClass():
print item
The important method is next() which returns the next item in the iteration. In this case, every time next() is invoked, we attempt to return the value of get() and increment the counter. Once there are no more items, we raise a StopIteration exception, which will gracefully exit the iteration.
Finally, you'll notice that MyClass defines a __iter__() method. This is what gives instances of MyClass that ability to be iterated over. The method simply returns a MyIterator instance.
Subscribe to:
Posts
(
Atom
)