Generators in Python.

The following examples are using Python 2.x but now after seeing Python 3.x released I’m interested in generators larger role in Python. Generators remind me of accumulators: generators accumulate a comprehensive result that you can add to with calls to yield. Take the following as an example.

def cubes(c):
    for i in range(c):
        yield i ** 3

What this code does is pretty obvious, except the yield statement. What does the function return – a generator. The generator can be used like a java iterator, and you add items to this iterable object by calling yield in your generator function. It can be used in several ways, like the following.

for i in cubes(10):
    print i, ';',

Or

x = cubes(10)
print x.next()
print x.next()
print x.next()

Eventually, using this approach, an exception will be thrown when you’ve exhausted the generator.

If you still want to use the result of the generator as a list, you can still do this. Simply cast the result to a list.

x = list(cubes(10))
print x

That is all I have to say about generator functions for now. They’re really interesting and somewhat useful, however, I’m not quite sold on the conversion to them as Python 3.x seems to be pushing. What will happen in Python 4.x?

Posted in Programming | Tagged | Leave a comment

Generate list of random integers in Python.

I use this for testing and that is about it.

import random
def randomArr(length, max):
    arr = []
    for i in range(0, length):
        arr.append(random.randint(0, max))
    return arr
Posted in Programming | Tagged , , | Leave a comment

Insertion sort in Python.

I’m losing faith in my programming skills today, so I’ve decided to re-implement sorting functions. Each day I’ll try to decrease the complexity of the algorithms, but, this day being the first, I’ll give you a quadratic insertion sort. This is an insertion sort, right, or is it shell sort? Heh…

def insertionSort(arr):
    for i in range(1, len(arr)):
        t = arr[i]
        for j in range(0, i):
            if(t < arr[j]):
                z = arr[j]
                arr[j] = t
                t = z
        arr[i] = t
    return arr

What should be next? Bubble sort? Heap sort? Come back tomorrow for a better algorithm. If you find a bug, please report it!

Posted in Programming | Tagged , , | Leave a comment


  • Ubuntu Logo Nagios Logo Jython Logo Hadoop Icon Apache Feather Icon Python Icon