def __init__(self): self.root = Tk() self.crono = Cronometro() self.frame = Frame(self.root) self.frame.pack() self.valor = StringVar() self.display = Label(self.frame, textvariable=self.valor, font=("Helvetica", 30)) self.display.pack(side=TOP, padx=10, pady=10) self.boton_iniciar = Button(self.frame, text="Iniciar/Detener", command=self.cambiar_estado) self.boton_iniciar.pack(side=LEFT) self.boton_borrar = Button(self.frame, text="Borrar", command=self.borrar) self.boton_borrar.pack(side=RIGHT) Thread.__init__(self) self.start() self.root.mainloop()
def main(): ''' Contem os comandos em Python referentes `a implementacao do algoritmo ''' seeds = [11, 7, 13, 19, 5189] tam = [50, 100, 250, 500, 1000] tempos = [] for i, seed in enumerate(seeds): numpy.random.seed(seed) vetor = gera_seq_aleatoria(tam[i]) cron = Cronometro() cron.Iniciar() conta_somas(vetor) cron.Parar() print("Tempo gasto com {0} elementos foi {1} segundos".format( tam[i], cron)) tempos.append(cron) del vetor del cron salvar_tempos(tempos)
class TkCronometro(Thread): def __init__(self): self.root = Tk() self.crono = Cronometro() self.frame = Frame(self.root) self.frame.pack() self.valor = StringVar() self.display = Label(self.frame, textvariable=self.valor, font=("Helvetica", 30)) self.display.pack(side=TOP, padx=10, pady=10) self.boton_iniciar = Button(self.frame, text="Iniciar/Detener", command=self.cambiar_estado) self.boton_iniciar.pack(side=LEFT) self.boton_borrar = Button(self.frame, text="Borrar", command=self.borrar) self.boton_borrar.pack(side=RIGHT) Thread.__init__(self) self.start() self.root.mainloop() def cambiar_estado(self): self.crono.cambiar_estado() def borrar(self): self.crono.borrar() def run(self): while True: if not self.crono.parado: self.crono.avanzar() sleep(0.5) self.valor.set(self.crono.get_tiempo()) def callback(self): self.root.quit()
es = r"path_to_file" delimiter = ";" conn = psycopg2.connect( "dbname='xxxxxx' user='******' host='xxxxxx' password='******'") conn.autocommit = True cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) start = time() print("Iniciando actualizacion de tablas y capas auxiliares") cur.execute("SELECT actualizar(%s, %s);", (es, delimiter)) cur.execute("SELECT vista_est();") cur.execute("DROP TABLE IF EXISTS xxxxxxx;") cur.execute("CREATE TABLE xxxxxx " "AS SELECT lado, st_union(the_geom) AS the_geom FROM parcels " "GROUP BY lado;") cur.execute("ALTER TABLE yyyy ADD COLUMN id SERIAL;") cur.execute("ALTER TABLE yyyy ADD PRIMARY KEY (id);") print("Actualizacion terminada") end = time() cr = Cronometro(start, end) cr.calculate_elapsed_time() conn.close()
def merge(left, right, merged): left_cursor, right_cursor = 0, 0 while left_cursor < len(left) and right_cursor < len(right): if left[left_cursor] <= right[right_cursor]: merged[left_cursor + right_cursor] = left[left_cursor] left_cursor += 1 else: merged[left_cursor + right_cursor] = right[right_cursor] right_cursor += 1 for left_cursor in range(left_cursor, len(left)): merged[left_cursor + right_cursor] = left[left_cursor] for right_cursor in range(right_cursor, len(right)): merged[left_cursor + right_cursor] = right[right_cursor] return merged for algorithm in (bubble_sort, merge_sort): algorithm_name = algorithm.__name__ numbers = list(range(10_000)) shuffle(numbers) with Cronometro(algorithm_name): algorithm(numbers)
from cronometro import Cronometro animals = ["zebra", "macaco", "elefante", "arara", "javali"] def bubble_sort(array): has_swapped = True num_of_iterations = 0 while has_swapped: has_swapped = False for i in range(len(array) - num_of_iterations - 1): if array[i] > array[i + 1]: array[i], array[i + 1] = array[i + 1], array[i] has_swapped = True num_of_iterations += 1 return array with Cronometro("bubble_sort"): bubble_sort(animals)
from cronometro import Cronometro c = Cronometro() for i in range(1000): c.avanzar() print(c.get_tiempo())
# armazena o número de iterações para evitar # a iteração sobre índices já ordenados num_of_iterations = 0 # Enquanto ainda não está ordenado (ocorreram trocas na iteração) while has_swapped: has_swapped = False # percorra o array até o ultimo índice não ordenado for i in range(len(array) - num_of_iterations - 1): # caso a posição corrente seja maior que a posterior if array[i] > array[i + 1]: # realiza a troca entre as posições array[i], array[i + 1] = array[i + 1], array[i] # marca que tivemos trocas nesta iteração has_swapped = True print(f"{num_of_iterations + 1}ª iteração:", array) num_of_iterations += 1 return array array = ["zebra", "macaco", "elefante", "arara", "javali"] with Cronometro("Bubble Sort"): bubble_sort(array) # print(bubble_sort([100, 4, 6, 33, 56, 67]))
current_position = current_position - 1 array[current_position] = current_value return array for algorithm in (insertion_sort, selection_sort): algorithm_name = algorithm.__name__ for input in (10_000, 100_000, 1_000_000): sorted_numbers = list(range(input)) reversed_sorted_numbers = list(reversed(sorted_numbers)) random_numbers = sorted_numbers[:] # copia dos ordenados shuffle(random_numbers) # embaralha eles with Cronometro(f"{algorithm_name} com entrada " + f"ordenada de {input} números"): algorithm(sorted_numbers) with Cronometro(f"{algorithm_name} com entrada " + f"inversamente ordenada de {input} números"): algorithm(reversed_sorted_numbers) with Cronometro(f"{algorithm_name} com entrada " + f"aleatória de {input} números"): algorithm(random_numbers) print("*" * 50)
# enquanto nenhumas das partes é percorrida por completo while left_cursor < len(left) and right_cursor < len(right): # compare os dois itens das partes e insira no array de mistura o menor if left[left_cursor] <= right[right_cursor]: merged[left_cursor + right_cursor] = left[left_cursor] left_cursor += 1 else: merged[left_cursor + right_cursor] = right[right_cursor] right_cursor += 1 # a iteração acima irá inserir os elementos de forma ordenada # quando uma das partes termina, devemos garantir # que a outra sera totalmente inserida no array de mistura # itera sobre os elementos restantes na partição "esquerda" # inserindo-os no array de mistura for left_cursor in range(left_cursor, len(left)): merged[left_cursor + right_cursor] = left[left_cursor] # itera sobre os elementos restantes na partição "direita" # inserindo-os no array de mistura for right_cursor in range(right_cursor, len(right)): merged[left_cursor + right_cursor] = right[right_cursor] return merged with Cronometro("merge_sort"): merge_sort([100, 4, 6, 33, 56, 67])