Posts tonen met het label python. Alle posts tonen
Posts tonen met het label python. Alle posts tonen

vrijdag 20 november 2009

bin-search for Python

Find function for sorted lists. In a sorted list we can do better than using 'find' which must look at each element in the array in turn. In this function we jump right in the middle of the array. If the middle element is the one we want, we're done. Otherwise, we search in the left or the right half of the vector. This depends on whether the object was less than or greater than the middle element. This example is taken from Paul Graham's 'ANSI Common Lisp', ch 4.

-----------------------
def binSearch(obj, vec):
    l = len(vec)
    if l != 0:
        return finder(obj, vec, 0, l-1)

def finder(obj, vec, start, end):
    r = end - start
    if r == 0:
        if obj == vec[int(start)]:
            return obj
        else:
            return 0
    else:
        mid = start + round(r / 2)
        obj2 = vec[int(mid)]
        if obj < obj2:
            return finder(obj, vec, start, mid-1)
        else:
            if obj > obj2:
                return finder(obj, vec, mid+1, end)
            else:
                return obj

woensdag 16 september 2009

Simpel uniq-script

infile = open(raw_input("Bestand: "), "r")
bestand = infile.readlines()
infile.close()

data = []

for line in bestand:
     if line not in data:
     data.append(line)

output = open(raw_input("Output: "), "w")

for regel in data:
    output.write(regel)
    output.close()

maandag 29 juni 2009

N(atural) L(anguage) T(ool)K(it)

Een aanrader: www.nltk.org.

De Natural Language TookKit is een set python modules voor allerlei taalkundige taken. Bij de modules komt ook een uitstekend boek waarin zowel veel basisvaardigheden voor het programmeren in Python als meer geavanceerde toepassingen aan bod komen.