Uno scrittoio digitale …

29 novembre 2012

Git

Archiviato in: code — admin @ 15:02

http://www.kernel.org/pub/software/scm/git/docs/everyday.html
http://git-scm.com/documentation
http://gitready.com/

11 novembre 2012

bpython

Archiviato in: code, python — Tag:, , , — admin @ 22:31

mai più senza … bpython

3 novembre 2012

Indice statico (3 caratteri)

Archiviato in: code, python — Tag:, , , , — admin @ 14:47

Gli script sono stati implementati per creare e manipolare seguenze di nucleotidi di DNA.

generate_dna.py

#!/usr/bin/python3
from random import choice
from hashing import alph

if __name__ == "__main__":
    out = ""
    collection = [x for x in alph.keys()]

    for x in range(9999): #max value = 9999999
        out += choice(collection)

    text_file = open("dna.txt", "w")
    text_file.write(out)
    text_file.close()

hashing.py

#!/usr/bin/python3
from itertools import tee
import time as t

alph = {'a':0, 'c':1, 'g':2, 't':3}

def time(f):
    def inner(*args, **kargs):
        t1 = t.time()
        result = f(*args, **kargs)
        t2 = t.time()

        if (t2 - t1 < 1):
            print ("[{0} took {1:.3} ms]".format(f.__name__, (t2-t1)*1000.0))
        else:
            print ("[{0} took {1:.3} s]".format(f.__name__, t2-t1))

        return result
    return inner

def blocks(iterable):
    a, b, c = tee(iterable, 3)

    next(b, None)
    next(c, None)
    next(c, None)

    return zip(a, b, c)

def hf(x):
    return sum([alph.get(z) * (len(alph) ** i) for i, z in enumerate(x)])

class Index:
    @time
    def __init__(self, source):
        self.d = dict()
        for i, x in enumerate(blocks(source)):
            index = hf(x)
            elem = i, "".join(x)
            if (index not in self.d):
                self.d[index] = [elem]
            else:
                self.d[index].append(elem)

    @time
    def count_key(self):
        return len(self.d.keys())

    @time
    def count_value(self):
        return sum([len(x) for x in self.d.values()])

    @time
    def search(self, elem):
        if (len(elem) == 3):
            index = hf(elem)
            return [x[0] for x in self.d[index]] if index in self.d else "not in index"
        else:
            raise LookupError("searching want string of 3 char!")

if __name__ == "__main__":
    text_file = open("dna.txt", "r")
    text = text_file.read()
    text_file.close()

    index = Index(text)
    print("keys: " + str(index.count_key()))
    print("values: " + str(index.count_value()))

    print(end='\n\n')
    print("get:", index.search("gat"), end='\n\n')
    print("agc:", index.search("agc"), end='\n\n')
    print("ccc:", index.search("ccc"), end='\n\n')

Funziona con WordPress