From 43abebd3dfb812a2f0f9fd587f92aae813e5520a Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Sun, 17 May 2020 19:43:59 -0300 Subject: [PATCH 1/8] converted to python3 --- src/python/Exponenciacao.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/python/Exponenciacao.py b/src/python/Exponenciacao.py index 8111b4b4..d61c0f05 100644 --- a/src/python/Exponenciacao.py +++ b/src/python/Exponenciacao.py @@ -1,9 +1,19 @@ +""" Algoritmo de exponenciação """ -def Exponenciacao(base, expoente): +def exponenciacao(base, expoente): + """ + Uma implementação simples de um algoritmo de exponenciação. + + Argumentos: + base: int. Base da operação + expoente: int. Expoente da operação. + + Retorna o resultado da opeaçao de exponenciação + """ result = base - for _ in xrange(0, expoente-1): + for _ in range(0, expoente-1): result *= base return result -print Exponenciacao(5, 2) -print Exponenciacao(5, 5) \ No newline at end of file +print(exponenciacao(5, 2)) +print(exponenciacao(5, 5)) From 2a0f64a5a08ac17d6377b15716ca6ed7266fd915 Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Mon, 18 May 2020 00:17:46 -0300 Subject: [PATCH 2/8] changed to python3 and checked using pylint --- src/python/BuscaBinaria.py | 21 ------- src/python/BuscaSentinela.py | 21 ------- src/python/BuscaSequencial.py | 19 ------- src/python/BuscaSequencialRecursiva.py | 21 ------- src/python/Exponenciacao.py | 4 +- src/python/ExponenciacaoRecursiva.py | 9 --- src/python/FatorialRecursiva.py | 7 --- src/python/Fibonacci.py | 37 +++++++----- src/python/InsertionSortIterativo.py | 12 ---- src/python/InsertionSortRecursivo.py | 17 ------ src/python/ListaSequencialOrdenada.py | 47 ---------------- src/python/MaxMinRecursivo.py | 13 ----- src/python/MaxRecursivoDC.py | 15 ----- src/python/MinMaxIterativo.py | 15 ----- src/python/PasseioDoCavalo.py | 56 ------------------- src/python/QuickSort.py | 34 ----------- src/python/SelectionSort.py | 24 -------- src/python/arrumarpasseio_do_cavalo.py | 56 +++++++++++++++++++ src/python/bubble_sort.py | 24 +++++--- src/python/busca_binaria.py | 29 ++++++++++ src/python/busca_sentinela.py | 30 ++++++++++ src/python/busca_sequencial.py | 42 ++++++++++++++ src/python/busca_sequencial_recursiva.py | 20 +++++++ src/python/calculate_pi.py | 13 ++++- src/python/exponenciacao_recursiva.py | 19 +++++++ src/python/fatorial.py | 18 ++++-- src/python/fatorial_recursivo.py | 17 ++++++ src/python/{HeapSort.py => heap_sort.py} | 12 ++-- src/python/insertion_sort_iterativo.py | 22 ++++++++ src/python/insertion_sort_recursivo.py | 28 ++++++++++ src/python/lista_sequencial_ordenada.py | 52 +++++++++++++++++ src/python/maximo_minimo_recursivo.py | 18 ++++++ src/python/maximo_recursivo_dc.py | 19 +++++++ src/python/{MergeSort.py => merge_sort.py} | 19 +++---- src/python/min_max_iterativo.py | 21 +++++++ src/python/pilha.py | 22 +++++--- src/python/quick_sort.py | 38 +++++++++++++ src/python/selection_sort.py | 34 +++++++++++ src/python/shellSort.py | 38 ------------- src/python/shell_sort.py | 52 +++++++++++++++++ .../{Soma2Numeros.py => soma_dois_numeros.py} | 21 +++++-- src/python/{timsort.py => tim_sort.py} | 30 +++++----- .../{TorreDeHanoi.py => torre_de_hanoi.py} | 5 +- 43 files changed, 629 insertions(+), 442 deletions(-) delete mode 100755 src/python/BuscaBinaria.py delete mode 100644 src/python/BuscaSentinela.py delete mode 100644 src/python/BuscaSequencial.py delete mode 100755 src/python/BuscaSequencialRecursiva.py delete mode 100755 src/python/ExponenciacaoRecursiva.py delete mode 100755 src/python/FatorialRecursiva.py delete mode 100644 src/python/InsertionSortIterativo.py delete mode 100755 src/python/InsertionSortRecursivo.py delete mode 100644 src/python/ListaSequencialOrdenada.py delete mode 100755 src/python/MaxMinRecursivo.py delete mode 100644 src/python/MaxRecursivoDC.py delete mode 100755 src/python/MinMaxIterativo.py delete mode 100644 src/python/PasseioDoCavalo.py delete mode 100644 src/python/QuickSort.py delete mode 100755 src/python/SelectionSort.py create mode 100644 src/python/arrumarpasseio_do_cavalo.py create mode 100644 src/python/busca_binaria.py create mode 100644 src/python/busca_sentinela.py create mode 100644 src/python/busca_sequencial.py create mode 100644 src/python/busca_sequencial_recursiva.py create mode 100644 src/python/exponenciacao_recursiva.py create mode 100644 src/python/fatorial_recursivo.py rename src/python/{HeapSort.py => heap_sort.py} (77%) create mode 100644 src/python/insertion_sort_iterativo.py create mode 100644 src/python/insertion_sort_recursivo.py create mode 100644 src/python/lista_sequencial_ordenada.py create mode 100644 src/python/maximo_minimo_recursivo.py create mode 100644 src/python/maximo_recursivo_dc.py rename src/python/{MergeSort.py => merge_sort.py} (75%) create mode 100644 src/python/min_max_iterativo.py create mode 100644 src/python/quick_sort.py create mode 100644 src/python/selection_sort.py delete mode 100644 src/python/shellSort.py create mode 100644 src/python/shell_sort.py rename src/python/{Soma2Numeros.py => soma_dois_numeros.py} (79%) rename src/python/{timsort.py => tim_sort.py} (78%) rename src/python/{TorreDeHanoi.py => torre_de_hanoi.py} (75%) mode change 100755 => 100644 diff --git a/src/python/BuscaBinaria.py b/src/python/BuscaBinaria.py deleted file mode 100755 index 49a450b3..00000000 --- a/src/python/BuscaBinaria.py +++ /dev/null @@ -1,21 +0,0 @@ -def BuscaBinaria(valor, vetor, esquerda, direita): - meio = int((esquerda+direita)/2) - - if esquerda <= direita: - - if valor > vetor[meio]: - esquerda = meio + 1 - return BuscaBinaria(valor, vetor, esquerda, direita) - elif valor < vetor[meio]: - direita = meio - 1 - return BuscaBinaria(valor, vetor, esquerda, direita) - else: - return meio - - else: - return -1 # Retorna -1 se o valor nao foi encontrado - - -vetor = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] -# Parametros, valor que quer procurar, vetor, comeco e fim do vetor -print BuscaBinaria(12, vetor, 0, len(vetor)) # Se encontrar retorna a posicao do valor no vetor, senao retorna -1 \ No newline at end of file diff --git a/src/python/BuscaSentinela.py b/src/python/BuscaSentinela.py deleted file mode 100644 index ae6c6e43..00000000 --- a/src/python/BuscaSentinela.py +++ /dev/null @@ -1,21 +0,0 @@ - -def busca_sentinela(l, value): - l.append(value) - index = 0 - while l[index] != value: - index = index + 1 - l.pop() - if index == len(l): - return -1 - return index - - -if __name__ == "__main__": - l = [1,9,2,8,7,4,5,6,4,3,10,0] - value = 4 - index = busca_sentinela(l, value) - print(l) - if index >= 0: - print("Found value {} at position {}.".format(value, index)) - else: - print("Could not find value {}.".format(value)) diff --git a/src/python/BuscaSequencial.py b/src/python/BuscaSequencial.py deleted file mode 100644 index fbedf4bc..00000000 --- a/src/python/BuscaSequencial.py +++ /dev/null @@ -1,19 +0,0 @@ -def SequentialSearch(value, array): - for x in xrange(0, len(array)): - if array[x] == value: - return x - return -1 - -def SentinelSearch(value, array): - array.append(value) # Puts the value at the end of the array - index = 0 - while array[index] != value: # While the value is different - index += 1 - array.pop() # Removes the value at the end of the array - if index == len(array)-1: # If the 'index' variable is the last position of the array, returns -1 - return -1 - return index # Else, returns the position of the value on the array - -array = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] -print SequentialSearch(54, array) -print SentinelSearch(98, array) \ No newline at end of file diff --git a/src/python/BuscaSequencialRecursiva.py b/src/python/BuscaSequencialRecursiva.py deleted file mode 100755 index 25254e5d..00000000 --- a/src/python/BuscaSequencialRecursiva.py +++ /dev/null @@ -1,21 +0,0 @@ -def busca_sequencial(valor, lista, tamanho): - """Busca sequencial recursiva. - - Returns: - Retorna o indice do valor na lista. - Se nao encontrar retorna -1. - """ - if tamanho == 0: - return -1 - else: - indice = busca_sequencial(valor, lista, tamanho-1) - if indice < 0: - if lista[tamanho-1] == valor: - indice = tamanho-1 - return indice - -if __name__ == '__main__': - lista = [1, 9, 39, 4, 12, 38, 94, 37] - for indice, valor in enumerate(lista): - print('Testando valor {} no indice {}'.format(valor, indice)) - assert busca_sequencial(valor, lista, len(lista)) == indice diff --git a/src/python/Exponenciacao.py b/src/python/Exponenciacao.py index d61c0f05..9b30b5f1 100644 --- a/src/python/Exponenciacao.py +++ b/src/python/Exponenciacao.py @@ -2,13 +2,13 @@ def exponenciacao(base, expoente): """ - Uma implementação simples de um algoritmo de exponenciação. + Implementação de um algoritmo de exponenciação. Argumentos: base: int. Base da operação expoente: int. Expoente da operação. - Retorna o resultado da opeaçao de exponenciação + Retorna o resultado da operação de exponenciação """ result = base for _ in range(0, expoente-1): diff --git a/src/python/ExponenciacaoRecursiva.py b/src/python/ExponenciacaoRecursiva.py deleted file mode 100755 index 926e75b6..00000000 --- a/src/python/ExponenciacaoRecursiva.py +++ /dev/null @@ -1,9 +0,0 @@ - -def Exponenciacao(base, expoente): - if expoente == 0: - return 1 - else: - return base * Exponenciacao(base, expoente-1) - -print Exponenciacao(5, 2) -print Exponenciacao(5, 5) \ No newline at end of file diff --git a/src/python/FatorialRecursiva.py b/src/python/FatorialRecursiva.py deleted file mode 100755 index 8eaf8224..00000000 --- a/src/python/FatorialRecursiva.py +++ /dev/null @@ -1,7 +0,0 @@ -def Fatorial(nro): - if nro == 1: - return 1 - else: - return nro * Fatorial(nro-1) - -print Fatorial(5) \ No newline at end of file diff --git a/src/python/Fibonacci.py b/src/python/Fibonacci.py index a660c45d..9c683890 100755 --- a/src/python/Fibonacci.py +++ b/src/python/Fibonacci.py @@ -1,34 +1,43 @@ +""" +Implementaço de vários algoritmos Fibonacci + +A lib "time" foi utilizada para marcar o tempo de +execução dos algoritmos em segundos +""" + import functools import time - -def fib_iterativa(n): - """Fibonnaci iterativa.""" +def fib_iterativa(number): + """Fibonacci iterativa.""" last = 0 curr = 1 - for _ in range(0, n): + for _ in range(0, number): last, curr = curr, curr + last return last -def fib_recursiva(n): +def fib_recursiva(number): """Fibonnaci recursiva.""" - if n < 2: - return n - return fib_recursiva(n-1) + fib_recursiva(n-2) + if number < 2: + return number + return fib_recursiva(number-1) + fib_recursiva(number-2) @functools.lru_cache(maxsize=None) -def fib_recursiva_com_cache(n): +def fib_recursiva_com_cache(number): """Fibonacci recursiva com cache.""" - if n < 2: - return n - return fib_recursiva_com_cache(n-1) + fib_recursiva_com_cache(n-2) + if number < 2: + return number + return fib_recursiva_com_cache(number-1) + fib_recursiva_com_cache(number-2) -def run_fibonacci(name, func, n=35): +def run_fibonacci(name, func, number=35): + """ + Roda o algoritmo e mostra o tempo de execução dele + """ start_time = time.time() - result = func(n) + result = func(number) diff_time = time.time() - start_time print('Fibonacci', name, ':', result, ':', '%.8f' % diff_time, 'segundos') diff --git a/src/python/InsertionSortIterativo.py b/src/python/InsertionSortIterativo.py deleted file mode 100644 index 84adf038..00000000 --- a/src/python/InsertionSortIterativo.py +++ /dev/null @@ -1,12 +0,0 @@ -def InsertionSort(vetor): - for x in range(1, len(vetor)): - chave = vetor[x] - aux = x-1 - while aux >= 0 and vetor[aux] > chave: - vetor[aux+1] = vetor[aux] - aux -= 1 - vetor[aux+1] = chave - return vetor - -vetor = [92, 23, 42, 12, 54, 65, 1, 2, 8, 9, 31, 99] -print InsertionSort(vetor) \ No newline at end of file diff --git a/src/python/InsertionSortRecursivo.py b/src/python/InsertionSortRecursivo.py deleted file mode 100755 index 95408349..00000000 --- a/src/python/InsertionSortRecursivo.py +++ /dev/null @@ -1,17 +0,0 @@ -def InsertionSort(vetor, indice): - aux = indice - while vetor[aux] < vetor[aux-1]: - temp = vetor[aux] - vetor[aux] = vetor[aux-1] - vetor[aux-1] = temp - aux -= 1 - if aux == 0: - break - if indice < len(vetor)-1: - InsertionSort(vetor, indice+1) - return vetor - -vetor = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] -print vetor -vetor = InsertionSort(vetor, 1) -print vetor \ No newline at end of file diff --git a/src/python/ListaSequencialOrdenada.py b/src/python/ListaSequencialOrdenada.py deleted file mode 100644 index b98db5c9..00000000 --- a/src/python/ListaSequencialOrdenada.py +++ /dev/null @@ -1,47 +0,0 @@ -# Lista Sequencial Dinamica e Ordenada - -import random - -lista = [] - -def inserirLista(chave, lista): - lista.append(chave) - i = 0 - while lista[i] < chave: - i += 1 - p = len(lista)-2 - while p >= i: - lista[p+1] = lista[p] - p -= 1 - lista[i] = chave - -def buscaSentinela(chave, lista): - lista.append(chave) - i = 0 - while lista[i] != chave: - i += 1 - if i == len(lista)-1: - lista.pop() - return -1 - lista.pop() - return i - -def deletaValor(chave, lista): - posicao = buscaSentinela(chave, lista) - if posicao >= 0: - lista.pop(posicao) - return True - else: - return False - -def mostraLista(lista): - print lista - -for x in xrange(0, 50): - inserirLista( random.randint(10,99) , lista) - -print 'Valor na posicao: ' + str(buscaSentinela(25, lista)) - -mostraLista(lista) -deletaValor(10, lista) -mostraLista(lista) \ No newline at end of file diff --git a/src/python/MaxMinRecursivo.py b/src/python/MaxMinRecursivo.py deleted file mode 100755 index cad2118a..00000000 --- a/src/python/MaxMinRecursivo.py +++ /dev/null @@ -1,13 +0,0 @@ -def MaxMin(vetor, minimo, maximo, indice): - if vetor[indice] < minimo: - minimo = vetor[indice] - if vetor[indice] > maximo: - maximo = vetor[indice] - if indice < len(vetor)-1: - MaxMin(vetor, minimo, maximo, indice+1) - else: - print minimo - print maximo - -vetor = [2, 94, 83, 10, 0, 2, 48, 1, 24] -MaxMin(vetor, vetor[0], vetor[0], 0) \ No newline at end of file diff --git a/src/python/MaxRecursivoDC.py b/src/python/MaxRecursivoDC.py deleted file mode 100644 index 3a477891..00000000 --- a/src/python/MaxRecursivoDC.py +++ /dev/null @@ -1,15 +0,0 @@ -# Exemplo de Maximo, utilizando recursao e divisao e conquista -def MaxDC(vetor, inicio, fim): - if inicio == fim: - return vetor[inicio] - meio = int( (inicio+fim)/2 ) - aux1 = MaxDC(vetor, inicio, meio) - aux2 = MaxDC(vetor, meio+1, fim) - if aux1 > aux2: - return aux1 - else: - return aux2 - -vetor = [19, 32, 43, 58, 12, 28, 98, 19, 12, 10] -print vetor -print '\nMax:' + str( MaxDC(vetor, 0, len(vetor)-1) ) \ No newline at end of file diff --git a/src/python/MinMaxIterativo.py b/src/python/MinMaxIterativo.py deleted file mode 100755 index b01fe902..00000000 --- a/src/python/MinMaxIterativo.py +++ /dev/null @@ -1,15 +0,0 @@ -def MinMaxArray(vetor): - minimo = vetor[0] - maximo = vetor[0] - - for x in xrange(1, len(vetor)): - if vetor[x] < minimo: - minimo = vetor[x] - elif vetor[x] > maximo: - maximo = vetor[x] - - print 'Minimo : ' + str(minimo) - print 'Maximo : ' + str(maximo) - -vetor = [2, 94, 83, 10, 0, 2, 48, 1, 24] -MinMaxArray(vetor) \ No newline at end of file diff --git a/src/python/PasseioDoCavalo.py b/src/python/PasseioDoCavalo.py deleted file mode 100644 index dacfc6a8..00000000 --- a/src/python/PasseioDoCavalo.py +++ /dev/null @@ -1,56 +0,0 @@ - -def Aceitavel(x, y): # Aceitavel se estiver dentro do tabuleiro e a casa ainda nao tiver sido visitada - Retorna True ou False - if x >= 0 and x <= num-1 and y >= 0 and y <= num-1 and tabuleiro[x][y] == 0: - return True - else: - return False - -def TentaMover(i, x, y): # Tenta o i-esimo movimento em (x,y), 1 <= i <= n^2 - done = i > numSqr # True ou False - k = 0 - while done == False and k < 8: - u = x + dx[k] # Coordenadas dos 8 movimentos possiveis do cavalo - v = y + dy[k] # Coordenadas dos 8 movimentos possiveis do cavalo - if Aceitavel(u, v): - tabuleiro[u][v] = i - done = TentaMover(i+1, u, v) # Tenta outro movimento - if done == False: - tabuleiro[u][v] = 0 # Sem sucesso, descarta movimento - k += 1 # Passa ao proximo movimento possivel - return done - -def MostraMovimento(x, y): - tabuleiro[x][y] = 1 - done = TentaMover(2, x, y) - string = "" - if done == True: - for x in xrange(0, num): - for y in xrange(0, num): - if tabuleiro[x][y] < 10: - string += "0" + str(tabuleiro[x][y]) + " " - else: - string += str(tabuleiro[x][y]) + " " - string += "\n" - print string - else: - print "Nao ha passeio possivel\n" - -dx = [2, 1, -1, -2, -2, -1, 1, 2] # Para calculo das coordenadas dos movimentos possiveis do cavalo (8 movimentos possiveis) -dy = [1, 2, 2, 1, -1, -2, -2, -1] # Para calculo das coordenadas dos movimentos possiveis do cavalo (8 movimentos possiveis) - -print "Digite o num de posicoes do tabuleiro: (ex.: 6) <= 10" -num = int(raw_input()) # Numero de posicoes do tabuleiro -print "Digite a posicao x onde o cavalo deve iniciar: (ex.: 1) >= 0" -x = int(raw_input()) # Numero de posicoes do tabuleiro -print "Digite a posicao y onde o cavalo deve iniciar: (ex.: 2) >= 0" -y = int(raw_input()) # Numero de posicoes do tabuleiro -numSqr = num * num # Numero total de casas - -print - -tabuleiro = [[],[],[],[],[],[],[],[],[],[]] # Tabuleiro maximo 20x20 -for x in xrange(0, num): - for y in xrange(0, num): - tabuleiro[x].append(0) -#print tabuleiro -MostraMovimento(x, y) \ No newline at end of file diff --git a/src/python/QuickSort.py b/src/python/QuickSort.py deleted file mode 100644 index 900557bc..00000000 --- a/src/python/QuickSort.py +++ /dev/null @@ -1,34 +0,0 @@ - -def swap(l, pos1, pos2): - temp = l[pos1] - l[pos1] = l[pos2] - l[pos2] = temp - -def partition(l, start, end): - pivot = l[start] - while True: - while l[start] < pivot: - start = start + 1 - - while l[end] > pivot: - end = end - 1 - - if start >= end: - return end - - swap(l, start, end) - - start = start + 1 - end = end - 1 - -def quick_sort(l, start, end): - if start < end: - p = partition(l, start, end) - quick_sort(l, start, p) - quick_sort(l, p+1, end) - -if __name__ == "__main__": - a = [9,8,5,7,6,2,4,3,1] - print(a) - quick_sort(a, 0, len(a)-1) - print(a) diff --git a/src/python/SelectionSort.py b/src/python/SelectionSort.py deleted file mode 100755 index ec17f0de..00000000 --- a/src/python/SelectionSort.py +++ /dev/null @@ -1,24 +0,0 @@ -def SelectionSort(vetor, indice): - - if indice >= len(vetor)-1: - return -1 - - minIndice = indice # minIndice vai guardar posicao onde esta o menor valor em relacao ao indice - - for x in xrange(indice+1, len(vetor)): - if vetor[x] < vetor[minIndice]: - minIndice = x - - temp = vetor[indice] - vetor[indice] = vetor[minIndice] - vetor[minIndice] = temp - - SelectionSort(vetor, indice+1) - - return vetor - -vetor = [82, 83, 92, 12, 23, 45, 64, 91, 73] - -print vetor -vetor = SelectionSort(vetor, 0) -print vetor diff --git a/src/python/arrumarpasseio_do_cavalo.py b/src/python/arrumarpasseio_do_cavalo.py new file mode 100644 index 00000000..9e7d9185 --- /dev/null +++ b/src/python/arrumarpasseio_do_cavalo.py @@ -0,0 +1,56 @@ + +def Aceitavel(x, y): # Aceitavel se estiver dentro do tabuleiro e a casa ainda nao tiver sido visitada - Retorna True ou False + if x >= 0 and x <= num-1 and y >= 0 and y <= num-1 and tabuleiro[x][y] == 0: + return True + else: + return False + +def TentaMover(i, x, y): # Tenta o i-esimo movimento em (x,y), 1 <= i <= n^2 + done = i > numSqr # True ou False + k = 0 + while done == False and k < 8: + u = x + dx[k] # Coordenadas dos 8 movimentos possiveis do cavalo + v = y + dy[k] # Coordenadas dos 8 movimentos possiveis do cavalo + if Aceitavel(u, v): + tabuleiro[u][v] = i + done = TentaMover(i+1, u, v) # Tenta outro movimento + if done == False: + tabuleiro[u][v] = 0 # Sem sucesso, descarta movimento + k += 1 # Passa ao proximo movimento possivel + return done + +def MostraMovimento(x, y): + tabuleiro[x][y] = 1 + done = TentaMover(2, x, y) + string = "" + if done == True: + for x in range(0, num): + for y in range(0, num): + if tabuleiro[x][y] < 10: + string += "0" + str(tabuleiro[x][y]) + " " + else: + string += str(tabuleiro[x][y]) + " " + string += "\n" + print(string) + else: + print("Nao ha passeio possivel\n") + +dx = [2, 1, -1, -2, -2, -1, 1, 2] # Para calculo das coordenadas dos movimentos possiveis do cavalo (8 movimentos possiveis) +dy = [1, 2, 2, 1, -1, -2, -2, -1] # Para calculo das coordenadas dos movimentos possiveis do cavalo (8 movimentos possiveis) + +print("Digite o num de posicoes do tabuleiro: (ex.: 6) <= 10") +num = int(input()) # Numero de posicoes do tabuleiro +print("Digite a posicao x onde o cavalo deve iniciar: (ex.: 1) >= 0") +x = int(input()) # Numero de posicoes do tabuleiro +print("Digite a posicao y onde o cavalo deve iniciar: (ex.: 2) >= 0") +y = int(input()) # Numero de posicoes do tabuleiro +numSqr = num * num # Numero total de casas + +print() + +tabuleiro = [[],[],[],[],[],[],[],[],[],[]] # Tabuleiro maximo 20x20 +for x in range(0, num): + for y in range(0, num): + tabuleiro[x].append(0) +#print tabuleiro +MostraMovimento(x, y) \ No newline at end of file diff --git a/src/python/bubble_sort.py b/src/python/bubble_sort.py index 5f5673a9..06eceb18 100755 --- a/src/python/bubble_sort.py +++ b/src/python/bubble_sort.py @@ -1,16 +1,26 @@ +""" Implementação do algoritmo bubble sort com recursão """ def bubble_sort(data, size): + """ + Implementação de um algoritmo de selection sort com recursão. + + Argumentos: + data: lista. Lista que será ordenada + size: int. Tamanho da lista + + Retorna a lista "data" ordenada. + """ swap = False - for x in range(0, size-1): - if data[x] > data[x+1]: - data[x], data[x+1] = data[x+1], data[x] + for i in range(0, size-1): + if data[i] > data[i+1]: + data[i], data[i+1] = data[i+1], data[i] swap = True if swap: bubble_sort(data, size-1) if __name__ == '__main__': - data = [2, 9, 8, 0, 1, 3, 5, 4, 6, 7] - print(data) - bubble_sort(data, len(data)) - print(data) + lista_nao_odenada = [2, 9, 8, 0, 1, 3, 5, 4, 6, 7] + print(lista_nao_odenada) + bubble_sort(lista_nao_odenada, len(lista_nao_odenada)) + print(lista_nao_odenada) diff --git a/src/python/busca_binaria.py b/src/python/busca_binaria.py new file mode 100644 index 00000000..cd421aa1 --- /dev/null +++ b/src/python/busca_binaria.py @@ -0,0 +1,29 @@ +""" Implementação do algoritmo de busca binária com recursão """ + +def busca_binaria(valor, vetor, esquerda, direita): + """ + Implementação de um algoritmo de busca binária com recursão. + + Argumentos: + valor: Any. Valor a ser buscado na lista + vetor: list. lista ordenada na qual o valor será buscado + esquerda: Any. Valor inicial da metade buscada + direita: Any. Valor final da metade buscada + + Retorna o índice do valor em "vetor" ou -1 caso não exista nela. + """ + meio = int((esquerda+direita)/2) + + if esquerda <= direita: + if valor > vetor[meio]: + esquerda = meio + 1 + return busca_binaria(valor, vetor, esquerda, direita) + elif valor < vetor[meio]: + direita = meio - 1 + return busca_binaria(valor, vetor, esquerda, direita) + return meio + return -1 + + +lista = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] +print(busca_binaria(12, lista, 0, len(lista))) diff --git a/src/python/busca_sentinela.py b/src/python/busca_sentinela.py new file mode 100644 index 00000000..38f36e00 --- /dev/null +++ b/src/python/busca_sentinela.py @@ -0,0 +1,30 @@ +""" Implementação do algoritmo de busca sentinela """ + +def busca_sentinela(list_to_search, value): + """ + Implementação de um algoritmo de busca sentinela. + + Argumentos: + value: Any. Valor a ser buscado na lista + list_to_search: list. lista na qual o valor será buscado + + Retorna o índice do valor em "list_to_search" ou -1 caso não exista nela. + """ + list_to_search.append(value) + list_index = 0 + while list_to_search[list_index] != value: + list_index = list_index + 1 + list_to_search.pop() + if list_index == len(list_to_search): + return -1 + return list_index + +if __name__ == "__main__": + some_list = [1, 9, 2, 8, 7, 4, 5, 6, 4, 3, 10, 0] + NUMBER_TO_FIND = 4 + NUMBER_INDEX = busca_sentinela(some_list, NUMBER_TO_FIND) + print(some_list) + if NUMBER_INDEX >= 0: + print("Found value {} at position {}.".format(NUMBER_TO_FIND, NUMBER_INDEX)) + else: + print("Could not find value {}.".format(NUMBER_TO_FIND)) diff --git a/src/python/busca_sequencial.py b/src/python/busca_sequencial.py new file mode 100644 index 00000000..087fa5a0 --- /dev/null +++ b/src/python/busca_sequencial.py @@ -0,0 +1,42 @@ +""" +Implementação dos algoritmos de busca sequencial e +busca sentinela +""" + +def sequential_search(value, array): + """ + Implementação de um algoritmo de busca sequencial. + + Argumentos: + value: Any. Valor a ser buscado na lista + array: list. lista na qual o valor será buscado + + Retorna o índice do valor em "array" ou -1 caso não exista nela. + """ + for i in range(0, len(array)): + if array[i] == value: + return i + return -1 + +def sentinel_search(value, array): + """ + Implementação de um algoritmo de busca sentinela. + + Argumentos: + value: Any. Valor a ser buscado na lista + array: list. lista na qual o valor será buscado + + Retorna o índice do valor em "array" ou -1 caso não exista nela. + """ + array.append(value) + index = 0 + while array[index] != value: + index += 1 + array.pop() + if index == len(array)-1: + return -1 + return index + +some_list = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67] +print(sequential_search(54, some_list)) +print(sentinel_search(98, some_list)) diff --git a/src/python/busca_sequencial_recursiva.py b/src/python/busca_sequencial_recursiva.py new file mode 100644 index 00000000..6a0a250a --- /dev/null +++ b/src/python/busca_sequencial_recursiva.py @@ -0,0 +1,20 @@ +""" Implementaçao do algoritmo de busca sequencial com recursão """ + +def busca_sequencial(valor, lista, index): + """Busca sequencial recursiva. + + Returns: + Retorna o indice do valor na lista. + Se nao encontrar retorna -1. + """ + if len(lista) == 0 or index == len(lista): + return -1 + if lista[index] == valor: + return index + return busca_sequencial(valor, lista, index+1) + +if __name__ == '__main__': + uma_lista = [1, 9, 39, 4, 12, 38, 94, 37] + for indice, valor_na_lista in enumerate(uma_lista): + print('Testando valor {} no indice {}'.format(valor_na_lista, indice)) + assert busca_sequencial(valor_na_lista, uma_lista, 0) == indice diff --git a/src/python/calculate_pi.py b/src/python/calculate_pi.py index b39bb793..f7cdb59a 100644 --- a/src/python/calculate_pi.py +++ b/src/python/calculate_pi.py @@ -1,9 +1,18 @@ +""" Implementaço de um algoritmo de cálculo do PI """ -def calculate_pi(n): +def calculate_pi(number): + """ + Implementação de um algoritmo de busca sequencial. + + Argumentos: + number: int. + + Retorna o valor de PI. + """ denominator = 1.0 operation = 1.0 pi = 0.0 - for _ in range(n): + for _ in range(number): pi += operation * (4.0 / denominator) denominator += 2.0 operation *= -1.0 diff --git a/src/python/exponenciacao_recursiva.py b/src/python/exponenciacao_recursiva.py new file mode 100644 index 00000000..4e9a65bd --- /dev/null +++ b/src/python/exponenciacao_recursiva.py @@ -0,0 +1,19 @@ +""" Algoritmo de exponenciação implementado com recursão """ + +def exponenciacao_recursiva(base, expoente): + """ + Implementação de um algoritmo de exponenciação. + + Argumentos: + base: int. Base da operação + expoente: int. Expoente da operação + + Retorna o resultado da operaçao de exponenciação. + """ + if expoente == 0: + return 1 + + return base * exponenciacao_recursiva(base, expoente-1) + +print(exponenciacao_recursiva(5, 2)) +print(exponenciacao_recursiva(5, 5)) diff --git a/src/python/fatorial.py b/src/python/fatorial.py index 598371f7..941ed364 100644 --- a/src/python/fatorial.py +++ b/src/python/fatorial.py @@ -1,8 +1,18 @@ +""" Uma implementação simples de um algoritmo fatorial """ + def fatorial(num): - aux = 1 - for x in range(2, num+1): - aux = aux * x - return aux + """ + Uma implementação simples de um algoritmo de fatorial. + + Argumentos: + num: int. o número do qual deseja-se obter o fatorial. + + Retorna o resultado da operação. + """ + aux = 1 + for i in range(2, num+1): + aux = aux * i + return aux if __name__ == '__main__': diff --git a/src/python/fatorial_recursivo.py b/src/python/fatorial_recursivo.py new file mode 100644 index 00000000..c91820a0 --- /dev/null +++ b/src/python/fatorial_recursivo.py @@ -0,0 +1,17 @@ +""" Algoritmo de fatorial implementado com recursão """ + +def fatorial_recursivo(numero): + """ + Implementação de um algoritmo de fatorial com recursão. + + Argumentos: + numero: int. o número do qual deseja-se obter o fatorial. + + Retorna o resultado da operação. + """ + if numero == 1: + return 1 + + return numero * fatorial_recursivo(numero-1) + +print(fatorial_recursivo(5)) diff --git a/src/python/HeapSort.py b/src/python/heap_sort.py similarity index 77% rename from src/python/HeapSort.py rename to src/python/heap_sort.py index dc3ca73c..d3aca40b 100644 --- a/src/python/HeapSort.py +++ b/src/python/heap_sort.py @@ -1,3 +1,4 @@ +""" Heap sort algorithm implementation """ def heap_sort(data): """Sort a list (data) in-place using HeapSort. @@ -6,7 +7,7 @@ def heap_sort(data): data (list): lista to be sorted. """ length = len(data) - index = length / 2 + index = length // 2 parent = 0 child = 0 temp = 0 @@ -36,8 +37,7 @@ def heap_sort(data): data[parent] = temp if __name__ == '__main__': - data = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] - print('Unsorted list: {}'.format(data)) - heap_sort(data) - print('Sorted list: {}'.format(data)) - + list_to_sort = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] + print('Unsorted list: {}'.format(list_to_sort)) + heap_sort(list_to_sort) + print('Sorted list: {}'.format(list_to_sort)) diff --git a/src/python/insertion_sort_iterativo.py b/src/python/insertion_sort_iterativo.py new file mode 100644 index 00000000..4f02d028 --- /dev/null +++ b/src/python/insertion_sort_iterativo.py @@ -0,0 +1,22 @@ +""" Implementação do algoritmo insertion sort iterativo """ + +def insertion_sort(vetor): + """ + Implementação de um algoritmo de insertion sort. + + Argumentos: + vetor: lista. Lista que será ordenada + + Retorna a lista "vetor" ordenada + """ + for i in range(1, len(vetor)): + chave = vetor[i] + aux = i-1 + while aux >= 0 and vetor[aux] > chave: + vetor[aux+1] = vetor[aux] + aux -= 1 + vetor[aux+1] = chave + return vetor + +lista_nao_ordenada = [92, 23, 42, 12, 54, 65, 1, 2, 8, 9, 31, 99] +print(insertion_sort(lista_nao_ordenada)) diff --git a/src/python/insertion_sort_recursivo.py b/src/python/insertion_sort_recursivo.py new file mode 100644 index 00000000..5678d415 --- /dev/null +++ b/src/python/insertion_sort_recursivo.py @@ -0,0 +1,28 @@ +""" Implementação do algoritmo insertion sort com recursão """ + +def insertion_sort_recursivo(vetor, indice): + """ + Implementação de um algoritmo de insertion sort com recursão. + + Argumentos: + vetor: lista. Lista que será ordenada + indice: int. Indice do elemento a ser ordenado na lista + + Retorna a lista "vetor" ordenada. + """ + aux = indice + while vetor[aux] < vetor[aux-1]: + temp = vetor[aux] + vetor[aux] = vetor[aux-1] + vetor[aux-1] = temp + aux -= 1 + if aux == 0: + break + if indice < len(vetor)-1: + insertion_sort_recursivo(vetor, indice+1) + return vetor + +lista_nao_ordenada = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] +print(lista_nao_ordenada) +lista_nao_ordenada = insertion_sort_recursivo(lista_nao_ordenada, 1) +print(lista_nao_ordenada) diff --git a/src/python/lista_sequencial_ordenada.py b/src/python/lista_sequencial_ordenada.py new file mode 100644 index 00000000..050c6fda --- /dev/null +++ b/src/python/lista_sequencial_ordenada.py @@ -0,0 +1,52 @@ +""" Lista Sequencial Dinamica e Ordenada """ + +import random + +lista = [] + +def inserir_lista(chave, lista): + """ + Insere a chave na lista + """ + lista.append(chave) + i = 0 + while lista[i] < chave: + i += 1 + p = len(lista) - 2 + while p >= i: + lista[p+1] = lista[p] + p -= 1 + lista[i] = chave + +def busca_sentinela(chave, lista): + """ Algoritmo de busca sentinela """ + lista.append(chave) + i = 0 + while lista[i] != chave: + i += 1 + if i == len(lista) - 1: + lista.pop() + return -1 + lista.pop() + return i + +def deleta_valor(chave, lista): + """ Deleta uma chave na lista """ + posicao = busca_sentinela(chave, lista) + if posicao >= 0: + lista.pop(posicao) + return True + return False + +def mostra_lista(lista): + """ Imprime a lista """ + print(lista) + +for _ in range(0, 50): + inserir_lista(random.randint(10, 99), lista) + +print('Valor na posicao: ' + str(busca_sentinela(25, lista))) + +mostra_lista(lista) +deleta_valor(10, lista) +mostra_lista(lista) diff --git a/src/python/maximo_minimo_recursivo.py b/src/python/maximo_minimo_recursivo.py new file mode 100644 index 00000000..67689515 --- /dev/null +++ b/src/python/maximo_minimo_recursivo.py @@ -0,0 +1,18 @@ +""" Implementação do algoritmo de máximo e mínimo com recursão """ + +def max_min(vetor, minimo, maximo, indice): + """ + Imprime os valores máximo e mínimo de um vetor + """ + if vetor[indice] < minimo: + minimo = vetor[indice] + if vetor[indice] > maximo: + maximo = vetor[indice] + if indice < len(vetor)-1: + max_min(vetor, minimo, maximo, indice+1) + else: + print(minimo) + print(maximo) + +um_vetor = [2, 94, 83, 10, 0, 2, 48, 1, 24] +max_min(um_vetor, um_vetor[0], um_vetor[0], 0) diff --git a/src/python/maximo_recursivo_dc.py b/src/python/maximo_recursivo_dc.py new file mode 100644 index 00000000..53979954 --- /dev/null +++ b/src/python/maximo_recursivo_dc.py @@ -0,0 +1,19 @@ +""" Exemplo de Maximo, utilizando recursao e divisao e conquista """ + +def max_dc(vetor, inicio, fim): + """ + Busca o valor máximo através da divisão e conquista. + Usa os valores início e fim para a recursão + """ + if inicio == fim: + return vetor[inicio] + meio = int((inicio+fim)/2) + aux1 = max_dc(vetor, inicio, meio) + aux2 = max_dc(vetor, meio+1, fim) + if aux1 > aux2: + return aux1 + return aux2 + +uma_lista = [19, 32, 43, 58, 12, 28, 98, 19, 12, 10] +print(uma_lista) +print('\nMax:' + str(max_dc(uma_lista, 0, len(uma_lista)-1))) diff --git a/src/python/MergeSort.py b/src/python/merge_sort.py similarity index 75% rename from src/python/MergeSort.py rename to src/python/merge_sort.py index d4ef4cbe..70933b54 100644 --- a/src/python/MergeSort.py +++ b/src/python/merge_sort.py @@ -1,15 +1,15 @@ +""" Merge sort algorithm implementation """ def merge_sort(data): - """Sort a list (data) in-place using merge sort approach. - + """ + Sorts a list (data) in-place using merge sort approach. Args: data (list): unsorted list. """ if len(data) < 2: return - - mid = len(data) / 2 - + mid = len(data) // 2 + left_data = data[:mid] right_data = data[mid:] @@ -40,8 +40,7 @@ def merge_sort(data): data_index += 1 if __name__ == '__main__': - data = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] - print('Unsorted list: {}'.format(data)) - merge_sort(data) - print('Sorted list: {}'.format(data)) - + some_list = [9, 1, 7, 6, 2, 8, 5, 3, 4, 0] + print('Unsorted list: {}'.format(some_list)) + merge_sort(some_list) + print('Sorted list: {}'.format(some_list)) diff --git a/src/python/min_max_iterativo.py b/src/python/min_max_iterativo.py new file mode 100644 index 00000000..d3b72f55 --- /dev/null +++ b/src/python/min_max_iterativo.py @@ -0,0 +1,21 @@ +""" +Implementação de um algoritmo que busca os valores máximo e mínimo +em um array +""" + +def min_max_array(vetor): + """ Busca os valores máximo e mínimo em vetor """ + minimo = vetor[0] + maximo = vetor[0] + + for i in range(1, len(vetor)): + if vetor[i] < minimo: + minimo = vetor[i] + elif vetor[i] > maximo: + maximo = vetor[i] + + print('Minimo : ' + str(minimo)) + print('Maximo : ' + str(maximo)) + +uma_lista = [2, 94, 83, 10, 0, 2, 48, 1, 24] +min_max_array(uma_lista) diff --git a/src/python/pilha.py b/src/python/pilha.py index 46c16369..1993ddf6 100644 --- a/src/python/pilha.py +++ b/src/python/pilha.py @@ -1,26 +1,34 @@ -import random +""" Implementação da estrutura de dados 'Pilha' """ +import random class Stack: - + """ + Essa classe implementa a estrutura de dados chamada "pilha" + """ def __init__(self): self.__stack = [] - + def push(self, value): + """ Adiciona o valor (value) ao final da pilha """ self.__stack.append(value) - + def pop(self): + """ Remove o último valor da pilha """ return self.__stack.pop() - + def show(self): + """ Imprime a pilha no console """ print(f'Stack: {self.__stack}') - def main(): + """ + Cria uma pilha e utiliza os métodos show, pop e push + """ stack = Stack() for _ in range(0, 10): - stack.push(random.randint(10,99)) + stack.push(random.randint(10, 99)) stack.show() diff --git a/src/python/quick_sort.py b/src/python/quick_sort.py new file mode 100644 index 00000000..e94000b2 --- /dev/null +++ b/src/python/quick_sort.py @@ -0,0 +1,38 @@ +""" Implementaçao do algoritmo quick sort """ + +def swap(a_list, pos1, pos2): + """ Troca a posição de dois itens em uma lista """ + temp = a_list[pos1] + a_list[pos1] = a_list[pos2] + a_list[pos2] = temp + +def partition(a_list, start, end): + """ Divide uma lista """ + pivot = a_list[start] + while True: + while a_list[start] < pivot: + start = start + 1 + + while a_list[end] > pivot: + end = end - 1 + + if start >= end: + return end + + swap(a_list, start, end) + + start = start + 1 + end = end - 1 + +def quick_sort(a_list, start, end): + """ Algoritmo de quick sort """ + if start < end: + part = partition(a_list, start, end) + quick_sort(a_list, start, part) + quick_sort(a_list, part+1, end) + +if __name__ == "__main__": + a = [9, 8, 5, 7, 6, 2, 4, 3, 1] + print(a) + quick_sort(a, 0, len(a)-1) + print(a) diff --git a/src/python/selection_sort.py b/src/python/selection_sort.py new file mode 100644 index 00000000..375e8472 --- /dev/null +++ b/src/python/selection_sort.py @@ -0,0 +1,34 @@ +""" Implementação de um algoritmo de selection sort com recursão """ + +def selection_sort(vetor, indice): + """ + Implementação de um algoritmo de selection sort com recursão. + + Argumentos: + vetor: lista. Lista que será ordenada + indice: int. Indice do elemento a ser ordenado na lista + + Retorna a lista "vetor" ordenada. + """ + if indice >= len(vetor)-1: + return -1 + + min_indice = indice # minIndice vai guardar posicao onde esta o menor valor em relacao ao indice + + for i in range(indice+1, len(vetor)): + if vetor[i] < vetor[min_indice]: + min_indice = i + + temp = vetor[indice] + vetor[indice] = vetor[min_indice] + vetor[min_indice] = temp + + selection_sort(vetor, indice+1) + + return vetor + +lista_nao_ordenada = [82, 83, 92, 12, 23, 45, 64, 91, 73] + +print(lista_nao_ordenada) +lista_nao_ordenada = selection_sort(lista_nao_ordenada, 0) +print(lista_nao_ordenada) diff --git a/src/python/shellSort.py b/src/python/shellSort.py deleted file mode 100644 index fb347027..00000000 --- a/src/python/shellSort.py +++ /dev/null @@ -1,38 +0,0 @@ -def shellSort(alist): - sublistcount = len(alist)//2 - while sublistcount > 0: - - for startposition in range(sublistcount): - gapInsertionSort(alist,startposition,sublistcount) - - sublistcount = sublistcount // 2 - -def gapInsertionSort(alist,start,gap): - for i in range(start+gap,len(alist),gap): - - currentvalue = alist[i] - position = i - - while position>=gap and alist[position-gap]>currentvalue: - alist[position]=alist[position-gap] - position = position-gap - - alist[position]=currentvalue - -alist = [54,26,93,17,77,31,44,55,20] -shellSort(alist) -print(alist) - -def shell(seq): - inc = len(seq) // 2 - while inc: - for i, el in enumerate(seq): - while i >= inc and seq[i - inc] > el: - seq[i] = seq[i - inc] - i -= inc - seq[i] = el - inc = 1 if inc == 2 else int(inc * 5.0 / 11) - -data = [22, 7, 2, -5, 8, 4] -shell(data) -print data # [-5, 2, 4, 7, 8, 22] \ No newline at end of file diff --git a/src/python/shell_sort.py b/src/python/shell_sort.py new file mode 100644 index 00000000..8d2a3036 --- /dev/null +++ b/src/python/shell_sort.py @@ -0,0 +1,52 @@ +""" Implementaçao do algoritmo shell sort """ + +def shell_sort(a_list): + """ + Algoritmo shell sort. + + Argumentos: + a_list: list. Uma lista não ordenada + """ + sublist_count = len(a_list)//2 + while sublist_count > 0: + for start_position in range(sublist_count): + gap_insertion_sort(a_list, start_position, sublist_count) + + sublist_count = sublist_count // 2 + +def gap_insertion_sort(a_list, start, gap): + """ + Algoritmo gap insertion sort. + """ + for i in range(start+gap, len(a_list), gap): + current_value = a_list[i] + position = i + while position >= gap and a_list[position-gap] > current_value: + a_list[position] = a_list[position - gap] + position = position - gap + + a_list[position] = current_value + +some_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] +shell_sort(some_list) +print(some_list) + +def shell(seq): + """ + Algoritmo de ordenação shell + + Argumentos: + seq: list. lista não ordenada + """ + inc = len(seq) // 2 + while inc: + for i, element in enumerate(seq): + while i >= inc and seq[i - inc] > element: + seq[i] = seq[i - inc] + i -= inc + seq[i] = element + inc = 1 if inc == 2 else int(inc * 5.0 / 11) + +data = [22, 7, 2, -5, 8, 4] +shell(data) +print(data) # [-5, 2, 4, 7, 8, 22] diff --git a/src/python/Soma2Numeros.py b/src/python/soma_dois_numeros.py similarity index 79% rename from src/python/Soma2Numeros.py rename to src/python/soma_dois_numeros.py index 9a3c20b6..c8998741 100644 --- a/src/python/Soma2Numeros.py +++ b/src/python/soma_dois_numeros.py @@ -1,10 +1,15 @@ +""" +Problem +Given an array/list A of n numbers and another number x, determines +if exists two elements in A whose sum is exactly x -# Problem -# Given an array/list A of n numbers and another number x, determines -# if exists two elements in A whose sum is exactly x - -# Works only for different values +Works only for different values +""" def solution1(values, expected): + """ + determines if exists two elements in + values whose sum is exactly expected + """ dic = {} for index, value in enumerate(values): dic[value] = index @@ -17,6 +22,10 @@ def solution1(values, expected): # Works with repeated values def solution2(values, expected): + """ + determines if exists two elements in + values whose sum is exactly expected + """ dic = {} for index, value in enumerate(values): diff = expected - value @@ -27,7 +36,7 @@ def solution2(values, expected): return False if __name__ == "__main__": - values = [42,5,9,9,16,16,13] + values = [42, 5, 9, 9, 16, 16, 13] print("Solution 1") diff --git a/src/python/timsort.py b/src/python/tim_sort.py similarity index 78% rename from src/python/timsort.py rename to src/python/tim_sort.py index 8e47cd57..0ff84766 100644 --- a/src/python/timsort.py +++ b/src/python/tim_sort.py @@ -1,11 +1,13 @@ -# Implementacao do algoritmo Timsort -# Referencia: https://www.geeksforgeeks.org/timsort/ +""" +Implementacao do algoritmo Timsort +Referencia: https://www.geeksforgeeks.org/timsort/ +""" RUN = 32 - def insertion_sort(data, left, right): - """Use insertion sort to sort the dataay from the left + """ + Use insertion sort to sort the dataay from the left index to the right index which is of size atmost RUN. """ for index in range(left+1, right+1): @@ -53,21 +55,21 @@ def merge_sort(data, left, mid, right): def timsort(data): """Iterative Timsort algorithm.""" - n = len(data) + data_size = len(data) # Sort individual sub lists of size RUN - for i in range(0, n, RUN): - insertion_sort(data, i, min((i+31), (n-1))) + for i in range(0, data_size, RUN): + insertion_sort(data, i, min((i+31), (data_size-1))) # Start merging from size RUN. # It will merge to form size 64, 128, 256 and so on size = RUN - while size < n: - for left in range(0, n, 2*size): + while size < data_size: + for left in range(0, data_size, 2*size): # Find ending point of left sub list # mid+1 is starting point of right sub dataay mid = left + size - 1 - right = min((left+2*size-1), (n-1)) + right = min((left+2*size-1), (data_size-1)) # Merge sub list data[left.....mid] & data[mid+1....right] merge_sort(data, left, mid, right) @@ -77,7 +79,7 @@ def timsort(data): if __name__ == '__main__': - data = [99, 15, 23, 0, -9, 1, 45, 2, 10, 15] - print('Unsorted data: ', data) - timsort(data) - print('Sorted data: ', data) + data_to_sort = [99, 15, 23, 0, -9, 1, 45, 2, 10, 15] + print('Unsorted data: ', data_to_sort) + timsort(data_to_sort) + print('Sorted data: ', data_to_sort) diff --git a/src/python/TorreDeHanoi.py b/src/python/torre_de_hanoi.py old mode 100755 new mode 100644 similarity index 75% rename from src/python/TorreDeHanoi.py rename to src/python/torre_de_hanoi.py index 3f727fdf..db1a0185 --- a/src/python/TorreDeHanoi.py +++ b/src/python/torre_de_hanoi.py @@ -1,5 +1,8 @@ +""" Implementaçao do algoritmo Torre de Hanoi """ + def hanoi(pino0, pino2, pino1, discos): - """Mostra os passos da torre de hanoi de forma recursiva. + """ + Mostra os passos da torre de hanoi de forma recursiva. Parametros: from, to, helper, numero de discos """ if discos == 1: From 55d005831a8d67f7bc5c3400af56cab1517c5231 Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Mon, 18 May 2020 10:27:10 -0300 Subject: [PATCH 3/8] converts from python2 to python3 --- src/python/arrumarpasseio_do_cavalo.py | 56 ------------ src/python/arvore_binaria_de_busca.py | 91 ++++++++++--------- src/python/{BinaryTree.py => binary_tree.py} | 34 ++++--- src/python/bubble_sort.py | 2 +- src/python/busca_em_labirinto.py | 20 ++-- src/python/calculate_pi.py | 2 +- src/python/fila.py | 13 +-- src/python/genetic_algorithm.py | 22 +++-- ...{ListaComPilhas.py => lista_com_pilhas.py} | 29 +++--- ...deada.py => lista_duplamente_encadeada.py} | 62 ++++++------- .../{ListaEncadeada.py => lista_encadeada.py} | 25 ++--- ...ircular.py => lista_encadeada_circular.py} | 9 +- ...nada.py => lista_encadeada_desordenada.py} | 2 +- src/python/lista_sequencial_ordenada.py | 2 +- src/python/passeio_do_cavalo.py | 66 ++++++++++++++ 15 files changed, 227 insertions(+), 208 deletions(-) delete mode 100644 src/python/arrumarpasseio_do_cavalo.py rename src/python/{BinaryTree.py => binary_tree.py} (89%) rename src/python/{ListaComPilhas.py => lista_com_pilhas.py} (71%) rename src/python/{ListaDuplamenteEncadeada.py => lista_duplamente_encadeada.py} (85%) rename src/python/{ListaEncadeada.py => lista_encadeada.py} (83%) rename src/python/{ListaEncadeadaCircular.py => lista_encadeada_circular.py} (98%) rename src/python/{ListaEncadeadaDesordenada.py => lista_encadeada_desordenada.py} (94%) create mode 100644 src/python/passeio_do_cavalo.py diff --git a/src/python/arrumarpasseio_do_cavalo.py b/src/python/arrumarpasseio_do_cavalo.py deleted file mode 100644 index 9e7d9185..00000000 --- a/src/python/arrumarpasseio_do_cavalo.py +++ /dev/null @@ -1,56 +0,0 @@ - -def Aceitavel(x, y): # Aceitavel se estiver dentro do tabuleiro e a casa ainda nao tiver sido visitada - Retorna True ou False - if x >= 0 and x <= num-1 and y >= 0 and y <= num-1 and tabuleiro[x][y] == 0: - return True - else: - return False - -def TentaMover(i, x, y): # Tenta o i-esimo movimento em (x,y), 1 <= i <= n^2 - done = i > numSqr # True ou False - k = 0 - while done == False and k < 8: - u = x + dx[k] # Coordenadas dos 8 movimentos possiveis do cavalo - v = y + dy[k] # Coordenadas dos 8 movimentos possiveis do cavalo - if Aceitavel(u, v): - tabuleiro[u][v] = i - done = TentaMover(i+1, u, v) # Tenta outro movimento - if done == False: - tabuleiro[u][v] = 0 # Sem sucesso, descarta movimento - k += 1 # Passa ao proximo movimento possivel - return done - -def MostraMovimento(x, y): - tabuleiro[x][y] = 1 - done = TentaMover(2, x, y) - string = "" - if done == True: - for x in range(0, num): - for y in range(0, num): - if tabuleiro[x][y] < 10: - string += "0" + str(tabuleiro[x][y]) + " " - else: - string += str(tabuleiro[x][y]) + " " - string += "\n" - print(string) - else: - print("Nao ha passeio possivel\n") - -dx = [2, 1, -1, -2, -2, -1, 1, 2] # Para calculo das coordenadas dos movimentos possiveis do cavalo (8 movimentos possiveis) -dy = [1, 2, 2, 1, -1, -2, -2, -1] # Para calculo das coordenadas dos movimentos possiveis do cavalo (8 movimentos possiveis) - -print("Digite o num de posicoes do tabuleiro: (ex.: 6) <= 10") -num = int(input()) # Numero de posicoes do tabuleiro -print("Digite a posicao x onde o cavalo deve iniciar: (ex.: 1) >= 0") -x = int(input()) # Numero de posicoes do tabuleiro -print("Digite a posicao y onde o cavalo deve iniciar: (ex.: 2) >= 0") -y = int(input()) # Numero de posicoes do tabuleiro -numSqr = num * num # Numero total de casas - -print() - -tabuleiro = [[],[],[],[],[],[],[],[],[],[]] # Tabuleiro maximo 20x20 -for x in range(0, num): - for y in range(0, num): - tabuleiro[x].append(0) -#print tabuleiro -MostraMovimento(x, y) \ No newline at end of file diff --git a/src/python/arvore_binaria_de_busca.py b/src/python/arvore_binaria_de_busca.py index 68778ba8..3900085b 100644 --- a/src/python/arvore_binaria_de_busca.py +++ b/src/python/arvore_binaria_de_busca.py @@ -1,7 +1,8 @@ - -# Arvore Binaria de Busca em Python -# Kelvin Salton do Prado -# 2015 +""" +Arvore Binaria de Busca em Python +Kelvin Salton do Prado +2015 +""" class Arvore: def __init__(self, chave): @@ -11,19 +12,19 @@ def __init__(self, chave): ############# Metodos de Busca ############# -def buscaRecursiva(no, chave): +def busca_recursiva(no, chave): if no is None: print(f'{chave} nao foi encontrado na arvore') - return None + return if no.chave == chave: print(f'{chave} foi encontrado na arvore') return no if chave > no.chave: - buscaRecursiva(no.direita, chave) + busca_recursiva(no.direita, chave) else: - buscaRecursiva(no.esquerda, chave) + busca_recursiva(no.esquerda, chave) -def buscaLinear(no, chave): +def busca_linear(no, chave): while no is not None: if no.chave == chave: return no @@ -43,36 +44,36 @@ def insere(no, chave): if chave < no.chave: no.esquerda = insere(no.esquerda, chave) else: - no.direita = insere(no.direita, chave) + no.direita = insere(no.direita, chave) return no ############################################ ########### Metodos de Impressao ########### -ImprimeArvore = '' +IMPRIME_ARVORE = '' -def preOrdem(no): - global ImprimeArvore +def pre_ordem(no): + global IMPRIME_ARVORE if no is None: return - ImprimeArvore += str(no.chave) + ', ' - preOrdem(no.esquerda) - preOrdem(no.direita) + IMPRIME_ARVORE += str(no.chave) + ', ' + pre_ordem(no.esquerda) + pre_ordem(no.direita) -def emOrdem(no): - global ImprimeArvore +def em_ordem(no): + global IMPRIME_ARVORE if no is None: return - emOrdem(no.esquerda) - ImprimeArvore += str(no.chave) + ', ' - emOrdem(no.direita) + em_ordem(no.esquerda) + IMPRIME_ARVORE += str(no.chave) + ', ' + em_ordem(no.direita) -def posOrdem(no): - global ImprimeArvore +def pos_ordem(no): + global IMPRIME_ARVORE if no is None: return - posOrdem(no.esquerda) - posOrdem(no.direita) - ImprimeArvore += str(no.chave) + ', ' + pos_ordem(no.esquerda) + pos_ordem(no.direita) + IMPRIME_ARVORE += str(no.chave) + ', ' ############################################ @@ -85,22 +86,22 @@ def maximo(a, b): def altura(no): if no is None: return 0 - return 1 + maximo( altura(no.esquerda), altura(no.direita) ) + return 1 + maximo(altura(no.esquerda), altura(no.direita)) ############################################ ########### Metodos de Exclusao ############ -def buscaNoPai(no, ch): - noPai = no +def busca_no_pai(no, ch): + no_pai = no while no is not None: if no.chave == ch: - return noPai - noPai = no + return no_pai + no_pai = no if no.chave < ch: no = no.direita else: no = no.esquerda - return noPai + return no_pai def maiorAesquerda(no): no = no.esquerda @@ -109,10 +110,10 @@ def maiorAesquerda(no): return no def exclui(no, ch): - atual = buscaLinear(no, ch) + atual = busca_linear(no, ch) if atual is None: return False - noPai = buscaNoPai(no, ch) + noPai = busca_no_pai(no, ch) if atual.esquerda is None or atual.direita is None: if atual.esquerda is None: substituto = atual.direita @@ -149,9 +150,9 @@ def exclui(no, ch): arvore = insere(arvore, 7) arvore = insere(arvore, 0) - buscaRecursiva(arvore, 6) # Busca que imprime na propria funcao + busca_recursiva(arvore, 6) # Busca que imprime na propria funcao - if buscaLinear(arvore, 6) is not None: # Retorna o NO ou None se nao encontrou + if busca_linear(arvore, 6) is not None: # Retorna o NO ou None se nao encontrou print('Valor encontrado') else: print('Valor nao encontrado') @@ -165,15 +166,15 @@ def exclui(no, ch): exclui(arvore, 3) # Chama os metodos de impressao - ImprimeArvore = "" - preOrdem(arvore) - print(f'PreOrdem: {ImprimeArvore}') - ImprimeArvore = "" - emOrdem(arvore) - print(f'EmOrdem: {ImprimeArvore}') - ImprimeArvore = "" - posOrdem(arvore) - print(f'PosOrdem: {ImprimeArvore}') + IMPRIME = "" + pre_ordem(arvore) + print(f'PreOrdem: {IMPRIME}') + IMPRIME = "" + em_ordem(arvore) + print(f'EmOrdem: {IMPRIME}') + IMPRIME = "" + pos_ordem(arvore) + print(f'PosOrdem: {IMPRIME}') # Mostra a altura da arvore apos remover os itens print(f'Altura: {altura(arvore)}') diff --git a/src/python/BinaryTree.py b/src/python/binary_tree.py similarity index 89% rename from src/python/BinaryTree.py rename to src/python/binary_tree.py index e868987d..f1de1cf2 100644 --- a/src/python/BinaryTree.py +++ b/src/python/binary_tree.py @@ -1,5 +1,6 @@ +""" Implementação de uma árvore binária """ -class Node(object): +class Node(): """ Node class store the data and the pointers to the next nodes (left and right). """ @@ -9,7 +10,7 @@ def __init__(self, data): self.data = data -class BinaryTree(object): +class BinaryTree(): """ Binary tree class provides some methods to insert, remove and print the data. """ @@ -28,18 +29,16 @@ def insert(self, data): if node.left is None: node.left = new_node break - else: - node = node.left + node = node.left else: if node.right is None: node.right = new_node break - else: - node = node.right + node = node.right def recursive_search(self, node, data): if node is None: - return None + return if node.data == data: return node @@ -118,8 +117,7 @@ def get_height(self, root): if height_right > height_left: return height_right + 1 - else: - return height_left + 1 + return height_left + 1 def level_order(self): height = self.get_height(self.root) @@ -130,7 +128,7 @@ def __print_level(self, node, level): if node is None: return if level == 1: - print "%d" % node.data, + print("%d" % node.data, end=' ') elif level > 1: self.__print_level(node.left, level-1) self.__print_level(node.right, level-1) @@ -139,13 +137,13 @@ def in_order(self, node): if node is None: return self.in_order(node.left) - print "%d" % node.data, + print("%d" % node.data, end=' ') self.in_order(node.right) def pre_order(self, node): if node is None: return - print "%d" % node.data, + print("%d" % node.data, end=' ') self.pre_order(node.left) self.pre_order(node.right) @@ -154,7 +152,7 @@ def post_order(self, node): return self.post_order(node.left) self.post_order(node.right) - print "%d" % node.data, + print("%d" % node.data, end=' ') b_tree = BinaryTree() @@ -165,11 +163,11 @@ def post_order(self, node): b_tree.insert(curr_data) b_tree.in_order(b_tree.root) -print '\n' +print('\n') b_tree.pre_order(b_tree.root) -print '\n' +print('\n') b_tree.post_order(b_tree.root) -print '\n' +print('\n') b_tree.level_order() -print '\n' -print b_tree.get_height(b_tree.root) \ No newline at end of file +print('\n') +print(b_tree.get_height(b_tree.root)) diff --git a/src/python/bubble_sort.py b/src/python/bubble_sort.py index 06eceb18..d31b1384 100755 --- a/src/python/bubble_sort.py +++ b/src/python/bubble_sort.py @@ -2,7 +2,7 @@ def bubble_sort(data, size): """ - Implementação de um algoritmo de selection sort com recursão. + Implementação de um algoritmo de ubble sort com recursão. Argumentos: data: lista. Lista que será ordenada diff --git a/src/python/busca_em_labirinto.py b/src/python/busca_em_labirinto.py index 8465a1ab..a157c58e 100644 --- a/src/python/busca_em_labirinto.py +++ b/src/python/busca_em_labirinto.py @@ -1,6 +1,8 @@ -# Busca em largura e em profundidade em um labirinto com o objetivo -# de encontrar um caminho do ponto "start" ao ponto "goal" -# Referencia: Problemas Classicos de Ciencia da Computacao com Python +""" +Busca em largura e em profundidade em um labirinto com o objetivo +de encontrar um caminho do ponto "start" ao ponto "goal" +Referencia: Problemas Classicos de Ciencia da Computacao com Python +""" from enum import Enum import random @@ -20,12 +22,12 @@ class Cell(Enum): class Maze: def __init__( - self, - rows = 10, - cols = 10, - sparseness = 0.2, - start = MazeLocation(0, 0), - goal = MazeLocation(9, 9) + self, + rows=10, + cols=10, + sparseness=0.2, + start=MazeLocation(0, 0), + goal=MazeLocation(9, 9) ): self._rows = rows self._cols = cols diff --git a/src/python/calculate_pi.py b/src/python/calculate_pi.py index f7cdb59a..9debf557 100644 --- a/src/python/calculate_pi.py +++ b/src/python/calculate_pi.py @@ -2,7 +2,7 @@ def calculate_pi(number): """ - Implementação de um algoritmo de busca sequencial. + Implementação de um algoritmo de cálculo do PI. Argumentos: number: int. diff --git a/src/python/fila.py b/src/python/fila.py index 9b9087f2..4b27d4a8 100644 --- a/src/python/fila.py +++ b/src/python/fila.py @@ -1,17 +1,18 @@ -import random +""" Implementação da estrutura de dados "fila" """ +import random class Queue: - + def __init__(self): self.__queue = [] - + def enqueue(self, value): self.__queue.append(value) - + def dequeue(self): return self.__queue.pop(0) - + def show(self): print(f'Queue: {self.__queue}') @@ -20,7 +21,7 @@ def main(): queue = Queue() for _ in range(0, 10): - queue.enqueue(random.randint(10,99)) + queue.enqueue(random.randint(10, 99)) queue.show() diff --git a/src/python/genetic_algorithm.py b/src/python/genetic_algorithm.py index d352856a..592cdfbd 100644 --- a/src/python/genetic_algorithm.py +++ b/src/python/genetic_algorithm.py @@ -1,6 +1,8 @@ -# Genetic algorithm example -# In this example we will create a generic genetic algorithm -# that can be applied to solve many problems. +""" +Genetic algorithm example +In this example we will create a generic genetic algorithm +that can be applied to solve many problems. +""" from enum import Enum from copy import deepcopy @@ -34,13 +36,13 @@ def mutate(self): class GeneticAlgorithm: def __init__( - self, - initial_population, - threshold, - max_generations=100, - mutation_chance=0.01, - crossover_chance=0.7, - selection_type=SelectionType.TOURNAMENT + self, + initial_population, + threshold, + max_generations=100, + mutation_chance=0.01, + crossover_chance=0.7, + selection_type=SelectionType.TOURNAMENT ): self._population = initial_population self._threshold = threshold diff --git a/src/python/ListaComPilhas.py b/src/python/lista_com_pilhas.py similarity index 71% rename from src/python/ListaComPilhas.py rename to src/python/lista_com_pilhas.py index 3aaa93b5..2a6940a3 100644 --- a/src/python/ListaComPilhas.py +++ b/src/python/lista_com_pilhas.py @@ -1,9 +1,10 @@ +""" +Problem: +Implement a queue with 2 stacks. Your queue should have an enqueue and +a dequeue function and it should be "first in first out" (FIFO). +""" -# Problem: -# Implement a queue with 2 stacks. Your queue should have an enqueue and -# a dequeue function and it should be "first in first out" (FIFO). - -class Stack(object): +class Stack(): def __init__(self): self.items = [] @@ -14,16 +15,16 @@ def push(self, item): def pop(self): return self.items.pop() - def isEmpty(self): + def is_empty(self): return not self.items def length(self): return len(self.items) - def at(self, index): + def position(self, index): return self.items[index] -class Queue(object): +class Queue(): def __init__(self): self.stack1 = Stack() @@ -33,21 +34,21 @@ def enqueue(self, item): self.stack1.push(item) def dequeue(self): - self.swapStack() + self.swap_stack() return self.stack2.pop() - def swapStack(self): + def swap_stack(self): # If the stack2 is empty, copy all elements from stack1 - if self.stack2.isEmpty(): - while not self.stack1.isEmpty(): + if self.stack2.is_empty(): + while not self.stack1.is_empty(): self.stack2.push(self.stack1.pop()) def __str__(self): output = [] for i in range(self.stack2.length()-1, -1, -1): - output.append(self.stack2.at(i)) + output.append(self.stack2.position(i)) for i in range(0, self.stack1.length()): - output.append(self.stack1.at(i)) + output.append(self.stack1.position(i)) return str(output) if __name__ == "__main__": diff --git a/src/python/ListaDuplamenteEncadeada.py b/src/python/lista_duplamente_encadeada.py similarity index 85% rename from src/python/ListaDuplamenteEncadeada.py rename to src/python/lista_duplamente_encadeada.py index cdae7986..1a69b3dc 100644 --- a/src/python/ListaDuplamenteEncadeada.py +++ b/src/python/lista_duplamente_encadeada.py @@ -1,28 +1,28 @@ +""" +Lista Duplamente Encadeada + +A cabeca da lista sempre 'aponta' para o primeiro no +O rabo da lista sempre 'aponta' para o ultimo no + +None <--- | 2 | ---> None +None <--- | 2 | <---> | 5 | ---> None +None <--- | 2 | <---> | 5 | <---> | 12 | ---> None +None <--- | 2 | <---> | 5 | <---> | 12 | <---> | 20 | ---> None +""" + +class No(): -# Lista Duplamente Encadeada -# -# A cabeca da lista sempre 'aponta' para o primeiro no -# O rabo da lista sempre 'aponta' para o ultimo no -# -# None <--- | 2 | ---> None -# None <--- | 2 | <---> | 5 | ---> None -# None <--- | 2 | <---> | 5 | <---> | 12 | ---> None -# None <--- | 2 | <---> | 5 | <---> | 12 | <---> | 20 | ---> None -# - -class No(object): - def __init__(self, dado, anterior, proximo): self.dado = dado self.anterior = anterior self.proximo = proximo - - -class ListaDuplamenteEncadeada(object): - + + +class ListaDuplamenteEncadeada(): + cabeca = None rabo = None - + def acrescentar(self, dado): """ Acrescenta um novo no a lista. """ # Cria um novo no apontando para None (anterior e proximo) @@ -43,12 +43,12 @@ def acrescentar(self, dado): self.rabo.proximo = novo_no # O rabo agora eh o novo no self.rabo = novo_no - + def remover(self, dado): """ Remove um no da lista. """ # O no atual eh o primeiro no da lista no_atual = self.cabeca - + # Vamos procurar pelo dado que queremos remover # Equanto o no atual for valido while no_atual is not None: @@ -68,16 +68,16 @@ def remover(self, dado): # O proximo do valor 2 passa a apontar para o 12 e # o anterior do valor 12 passa a apontar para o 2 # --------------- - # ... <---> | 2 | <---|--- | 5 | ---|---> | 12 | <---> ... + # ... <---> | 2 | <---|--- | 5 | ---|---> | 12 | <---> ... no_atual.anterior.proximo = no_atual.proximo no_atual.proximo.anterior = no_atual.anterior # Se nao eh o no que estamos buscando va para o proximo no_atual = no_atual.proximo - + def mostrar(self): """ Mostra todos os dados da lista. """ - print "Lista Duplamente Encadeada:" + print("Lista Duplamente Encadeada:") # O no atual eh o primeiro no da lista no_atual = self.cabeca @@ -90,14 +90,14 @@ def mostrar(self): no += "<---> | " + str(no_atual.dado) + " | " if no_atual.proximo is None: no += "<---> None" - + no_atual = no_atual.proximo - print no - print "="*80 - - + print(no) + print("="*80) + + lista = ListaDuplamenteEncadeada() - + lista.acrescentar(2) lista.mostrar() lista.acrescentar(5) @@ -106,8 +106,8 @@ def mostrar(self): lista.mostrar() lista.acrescentar(20) lista.mostrar() - + lista.remover(12) lista.mostrar() lista.remover(5) -lista.mostrar() \ No newline at end of file +lista.mostrar() diff --git a/src/python/ListaEncadeada.py b/src/python/lista_encadeada.py similarity index 83% rename from src/python/ListaEncadeada.py rename to src/python/lista_encadeada.py index c1bbf636..dcfb3d84 100644 --- a/src/python/ListaEncadeada.py +++ b/src/python/lista_encadeada.py @@ -1,28 +1,29 @@ +""" +!/usr/bin/env python +-*- coding: utf-8 -*- -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# Lista Ligada: -# _________ _________ _________ _________ -# head --> | 2 | --|--> | 1 | --|--> | 5 | --|--> | 3 | --|--> None -# --------- --------- --------- --------- +Lista Ligada: + _________ _________ _________ _________ +head --> | 2 | --|--> | 1 | --|--> | 5 | --|--> | 3 | --|--> None + --------- --------- --------- --------- +""" class Node: - - def __init__(self, value, next_node = None): + + def __init__(self, value, next_node=None): self.__value = value self.next_node = next_node - + @property def value(self): return self.__value class LinkedList: - + def __init__(self): self.__main_node = None - + def append(self, value): if self.__main_node is None: self.__main_node = Node(value) diff --git a/src/python/ListaEncadeadaCircular.py b/src/python/lista_encadeada_circular.py similarity index 98% rename from src/python/ListaEncadeadaCircular.py rename to src/python/lista_encadeada_circular.py index e2bc535d..1904b579 100644 --- a/src/python/ListaEncadeadaCircular.py +++ b/src/python/lista_encadeada_circular.py @@ -1,5 +1,9 @@ +""" implementação de uma lista encadeada circular """ + +import unittest + class Node: - + def __init__(self, value): self.__value = value self.next = None @@ -8,7 +12,7 @@ def get_value(self): return self.__value class CircularlyLinkedList: - + def __init__(self): self.__head = None self.__tail = None @@ -76,7 +80,6 @@ def remove(self, value): if not found: raise ValueError(str(value) + ' not found in list') -import unittest class TestCircularlyLinkedList(unittest.TestCase): diff --git a/src/python/ListaEncadeadaDesordenada.py b/src/python/lista_encadeada_desordenada.py similarity index 94% rename from src/python/ListaEncadeadaDesordenada.py rename to src/python/lista_encadeada_desordenada.py index 7709c571..f6904ad2 100644 --- a/src/python/ListaEncadeadaDesordenada.py +++ b/src/python/lista_encadeada_desordenada.py @@ -1,4 +1,4 @@ - +""" Implementação de uma lista encadeada desordenada """ class Node: def __init__(self, value, next_node=None): diff --git a/src/python/lista_sequencial_ordenada.py b/src/python/lista_sequencial_ordenada.py index 050c6fda..fd875272 100644 --- a/src/python/lista_sequencial_ordenada.py +++ b/src/python/lista_sequencial_ordenada.py @@ -9,7 +9,7 @@ def inserir_lista(chave, lista): Insere a chave na lista """ lista.append(chave) - i = 0 + i, p = 0, 0 while lista[i] < chave: i += 1 p = len(lista) - 2 diff --git a/src/python/passeio_do_cavalo.py b/src/python/passeio_do_cavalo.py new file mode 100644 index 00000000..c08795d9 --- /dev/null +++ b/src/python/passeio_do_cavalo.py @@ -0,0 +1,66 @@ +""" Implementação do algoritmo passeio do cavalo """ + +def aceitavel(x, y): + """ + Aceitavel se estiver dentro do tabuleiro e a casa ainda nao tiver sido + visitada + + Retorna True ou False + """ + if x >= 0 and x <= num-1 and y >= 0 and y <= num-1 and tabuleiro[x][y] == 0: + return True + else: + return False + +def tenta_mover(i, x, y): + """ + Tenta o i-esimo movimento em (x,y), 1 <= i <= n^2 + """ + done = i > numSqr # True ou False + k = 0 + while done == False and k < 8: + u = x + dx[k] # Coordenadas dos 8 movimentos possiveis do cavalo + v = y + dy[k] # Coordenadas dos 8 movimentos possiveis do cavalo + if aceitavel(u, v): + tabuleiro[u][v] = i + done = tenta_mover(i+1, u, v) # Tenta outro movimento + if done == False: + tabuleiro[u][v] = 0 # Sem sucesso, descarta movimento + k += 1 # Passa ao proximo movimento possivel + return done + +def mostra_movimento(x, y): + tabuleiro[x][y] = 1 + done = tenta_mover(2, x, y) + string = "" + if done == True: + for x in range(0, num): + for y in range(0, num): + if tabuleiro[x][y] < 10: + string += "0" + str(tabuleiro[x][y]) + " " + else: + string += str(tabuleiro[x][y]) + " " + string += "\n" + print(string) + else: + print("Nao ha passeio possivel\n") + +dx = [2, 1, -1, -2, -2, -1, 1, 2] +dy = [1, 2, 2, 1, -1, -2, -2, -1] + +print("Digite o num de posicoes do tabuleiro: (ex.: 6) <= 10") +num = int(input()) # Numero de posicoes do tabuleiro +print("Digite a posicao x onde o cavalo deve iniciar: (ex.: 1) >= 0") +x = int(input()) # Numero de posicoes do tabuleiro +print("Digite a posicao y onde o cavalo deve iniciar: (ex.: 2) >= 0") +y = int(input()) # Numero de posicoes do tabuleiro +numSqr = num * num # Numero total de casas + +print() + +tabuleiro = [[], [], [], [], [], [], [], [], [], []] # Tabuleiro maximo 20x20 +for x in range(0, num): + for y in range(0, num): + tabuleiro[x].append(0) +#print tabuleiro +mostra_movimento(x, y) From 06660304bcb65cc640aafe2722c02991da13fca8 Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Sun, 24 May 2020 11:51:59 -0300 Subject: [PATCH 4/8] renames file --- src/python/{fatorial_recursivo.py => fatorial_recursiva.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/python/{fatorial_recursivo.py => fatorial_recursiva.py} (100%) diff --git a/src/python/fatorial_recursivo.py b/src/python/fatorial_recursiva.py similarity index 100% rename from src/python/fatorial_recursivo.py rename to src/python/fatorial_recursiva.py From 5ef8d71c376a141c24e62f255c3f3d3482668fa3 Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Sun, 24 May 2020 11:52:06 -0300 Subject: [PATCH 5/8] updates readme --- README.md | 56 +++++++++++++++++++++++++++---------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 33e12dc5..52f5c806 100644 --- a/README.md +++ b/README.md @@ -8,41 +8,41 @@ Com o objetivo de alcançar uma abrangência maior e encorajar novas pessoas a c |-------------------------------------|-------|------|--------|----|------|------------|--------| | [Algoritmo Dijkstra][1] | [C/C++](/src/c/AlgoritmoDijkstra.c) | Java | Python | Go | Ruby | Javascript | Pascal | | [Algoritmo Floyd Warshall][2] | [C/C++](/src/c/AlgoritmoFloydWarshall.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| [Busca Binária][5] | [C/C++](/src/c/BinarySearch.cpp) | Java | [Python](/src/python/BuscaBinaria.py) | Go | [Ruby](/src/ruby/BuscaBinaria.rb) | Javascript | [Pascal](/src/pascal/busca-binaria.pas) | +| [Busca Binária][5] | [C/C++](/src/c/BinarySearch.cpp) | Java | [Python](/src/python/busca_binaria.py) | Go | [Ruby](/src/ruby/BuscaBinaria.rb) | Javascript | [Pascal](/src/pascal/busca-binaria.pas) | | [Busca em Grafos][6] | [C/C++](/src/c/BuscaEmGrafo.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| [Busca Sequencial][7] | C/C++ | Java | [Python](/src/python/BuscaSequencial.py) | Go | [Ruby](/src/ruby/BuscaSequencial.rb) | [Javascript](/src/javascript/BuscaLinear.js) | Pascal | -| [Busca Sequencial Recursiva][8] | C/C++ | Java | [Python](/src/python/BuscaSequencialRecursiva.py) | Go | Ruby | Javascript | Pascal | -| [Busca utilizando Sentinela][9] | [C/C++](/src/c/BuscaSentinela.c) | Java | [Python](/src/python/BuscaSentinela.py) | Go | [Ruby](/src/ruby/BuscaSentinela.rb) | Javascript | Pascal | +| [Busca Sequencial][7] | C/C++ | Java | [Python](/src/python/busca_sequencial.py) | Go | [Ruby](/src/ruby/BuscaSequencial.rb) | [Javascript](/src/javascript/BuscaLinear.js) | Pascal | +| [Busca Sequencial Recursiva][8] | C/C++ | Java | [Python](/src/python/busca_sequencial_recursiva.py) | Go | Ruby | Javascript | Pascal | +| [Busca utilizando Sentinela][9] | [C/C++](/src/c/BuscaSentinela.c) | Java | [Python](/src/python/busca_sentinela.py) | Go | [Ruby](/src/ruby/BuscaSentinela.rb) | Javascript | Pascal | | Busca por Interpolação | [C/C++](/src/c/Interpolation_search.cpp) | Java | Python | Go | Ruby | Javascript | Pascal | | [Caixeiro Viajante][10] | [C/C++](/src/c/CaixeiroViajante.c) | Java | Python | [Go](/src/go/caixeiroviajante/caixeiroviajante.go) | Ruby | Javascript | Pascal | | [Ciclo Hamiltoniano][11] | [C/C++](/src/c/CicloHamiltoniano.c) | Java | Python | Go | Ruby | Javascript | Pascal | | [Componentes Conexos][12] | [C/C++](/src/c/ComponentesConexos.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| [Exponenciação][13] | [C/C++](/src/c/Exponenciacao.c) | Java | [Python](/src/python/Exponenciacao.py) | [Go](/src/go/exponenciacao/exponenciacao.go) | [Ruby](/src/ruby/Exponenciacao.rb) | Javascript | Pascal | -| [Exponenciação Recursiva][14] | [C/C++](/src/c/ExponenciacaoRecursiva.c) | Java | [Python](/src/python/ExponenciacaoRecursiva.py) | Go | [Ruby](/src/ruby/ExponenciacaoRecursiva.rb) | Javascript | Pascal | +| [Exponenciação][13] | [C/C++](/src/c/Exponenciacao.c) | Java | [Python](/src/python/exponenciacao.py) | [Go](/src/go/exponenciacao/exponenciacao.go) | [Ruby](/src/ruby/Exponenciacao.rb) | Javascript | Pascal | +| [Exponenciação Recursiva][14] | [C/C++](/src/c/ExponenciacaoRecursiva.c) | Java | [Python](/src/python/exponenciacao_recursiva.py) | Go | [Ruby](/src/ruby/ExponenciacaoRecursiva.rb) | Javascript | Pascal | | [Fatorial][15] | [C/C++](/src/c/Fatorial.c) | [Java](/src/java/Fatorial.java) | [Python](/src/python/fatorial.py) | [Go](/src/go/fatorial/fatorial.go) | [Ruby](/src/ruby/Fatorial.rb) | Javascript | [Pascal](/src/pascal/fatorial.py) | -| [Fatorial Recursiva][16] | [C/C++](/src/c/FatorialRecursiva.c) | [Java](/src/java/FatorialRecursiva.java) | [Python](/src/python/FatorialRecursiva.py) | Go | [Ruby](/src/ruby/Fatorial.rb) | Javascript | [Pascal](src/pascal/fatorial-recusiva.pas) | -| [Fibonacci][17] | [C/C++](/src/c/Fibonacci.cpp) | [Java](/src/java/Fibonacci.java) | [Python](/src/python/Fibonacci.py) | [Go](/src/go/fibonacci/fibonacci.go) | [Ruby](/src/ruby/Fibonacci.rb) | Javascript | Pascal | +| [Fatorial Recursiva][16] | [C/C++](/src/c/FatorialRecursiva.c) | [Java](/src/java/FatorialRecursiva.java) | [Python](/src/python/fatorial_recursiva.py) | Go | [Ruby](/src/ruby/Fatorial.rb) | Javascript | [Pascal](src/pascal/fatorial-recusiva.pas) | +| [Fibonacci][17] | [C/C++](/src/c/Fibonacci.cpp) | [Java](/src/java/Fibonacci.java) | [Python](/src/python/fibonacci.py) | [Go](/src/go/fibonacci/fibonacci.go) | [Ruby](/src/ruby/Fibonacci.rb) | Javascript | Pascal | | [Máximo Recursivo][26] | [C/C++](/src/c/MaxRecursivo.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| [Mínimo e Máximo Iterativo][27] | C/C++ | [Java](/src/java/MaxMinArray.java) | [Python](/src/python/MinMaxIterativo.py) | Go | Ruby | Javascript | Pascal | -| [Mínimo e Máximo Recursivo][28] | [C/C++](/src/c/MaxMinRecursivo.c) | Java | [Python](/src/python/MaxMinRecursivo.py) | [Go](/src/go/maximominimo/MaximoMinimo.go) | Ruby | Javascript | Pascal | -| Mínimo e Máximo Divisão e Conquista | C/C++ | Java | [Python](/src/python/MaxRecursivoDC.py) | [Go](/src/go/maximominimo/MaximoMinimo.go) | Ruby | Javascript | Pascal | -| [Passeio do Cavalo][30] | C/C++ | Java | [Python](/src/python/PasseioDoCavalo.py) | Go | Ruby | Javascript | Pascal | -| [Torre de Hanói][33] | C/C++ | [Java](/src/java/TorreDeHanoi.java) | [Python](/src/python/TorreDeHanoi.py) | [Go](/src/go/hanoi/hanoi.go) | [Ruby](/src/ruby/Hanoi.rb) | Javascript | Pascal | +| [Mínimo e Máximo Iterativo][27] | C/C++ | [Java](/src/java/MaxMinArray.java) | [Python](/src/python/min_max_iterativo.py) | Go | Ruby | Javascript | Pascal | +| [Mínimo e Máximo Recursivo][28] | [C/C++](/src/c/MaxMinRecursivo.c) | Java | [Python](/src/python/maximo_minimo_recursivo.py) | [Go](/src/go/maximominimo/MaximoMinimo.go) | Ruby | Javascript | Pascal | +| Mínimo e Máximo Divisão e Conquista | C/C++ | Java | [Python](/src/python/maximo_recursivo_dc.py) | [Go](/src/go/maximominimo/MaximoMinimo.go) | Ruby | Javascript | Pascal | +| [Passeio do Cavalo][30] | C/C++ | Java | [Python](/src/python/passeio_do_cavalo.py) | Go | Ruby | Javascript | Pascal | +| [Torre de Hanói][33] | C/C++ | [Java](/src/java/TorreDeHanoi.java) | [Python](/src/python/torre_de_hanoi.py) | [Go](/src/go/hanoi/hanoi.go) | [Ruby](/src/ruby/Hanoi.rb) | Javascript | Pascal | | [Algoritmo Genético][51] | C/C++ | Java | [Python](/src/python/genetic_algorithm.py) | Go | Ruby | Javascript | Pascal | | Estruturas de Dados | C/C++ | Java | Python | Go | Ruby | Javascript | Pascal | |-------------------------------------|-------|------|--------|----|------|------------|--------| | [Árvore Binária de Busca][3] | [C/C++](/src/c/ArvoreBinariaDeBusca.c) | [Java](/src/java/ArvoreDeBuscaBinaria.java) | [Python](/src/python/arvore_binaria_de_busca.py) | Go | Ruby | [Javascript](/src/javascript/ArvoreDeBuscaBinaria.js) | Pascal | -| [Árvore Binária Utilizando Classes][4] | C/C++ | Java | [Python](/src/python/BinaryTree.py) | Go | Ruby | Javascript | Pascal | +| [Árvore Binária Utilizando Classes][4] | C/C++ | Java | [Python](/src/python/binary_tree.py) | Go | Ruby | Javascript | Pascal | | [Deque][54] | C/C++ | Java | Python | Go | Ruby | [Javascript](/src/javascript/Deque.js) | Pascal | | [Fila][18] | [C/C++](/src/c/Fila.c) | [Java](/src/java/Fila.java) | [Python](/src/python/fila.py) | Go | [Ruby](/src/ruby/Fila.rb) | [Javascript](/src/javascript/Fila.js) | Pascal | | [Fila Encadeada Dinâmica][19] | [C/C++](/src/c/FilaEncadeadaDinamica.c) | Java | Python | Go | Ruby | Javascript | Pascal | | [Grafo][20] | [C/C++](/src/c/Grafos.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| [Lista Circular Ligada][52] | [C/C++](/src/c/ListaCircularLigada.c) | Java | [Python](/src/python/ListaEncadeadaCircular.py) | Go | Ruby | Javascript | Pascal | -| [Lista Encadeada][22] | C/C++ | Java | [Python](/src/python/ListaEncadeada.py) | Go | Ruby | [Javascript](/src/javascript/ListaSimplesmenteEncadeada.js) | Pascal | -| [Lista Duplamente Encadeada][23] | [C/C++](/src/c/ListaDuplamenteEncadeada.c) | [Java](/src/java/ListaDuplamenteEncadeada.java) | [Python](/src/python/ListaDuplamenteEncadeada.py) | Go | Ruby | [Javascript](/src/javascript/ListaDumplamenteEncadeada.js) | Pascal | +| [Lista Circular Ligada][52] | [C/C++](/src/c/ListaCircularLigada.c) | Java | [Python](/src/python/lista_encadeada_circular.py) | Go | Ruby | Javascript | Pascal | +| [Lista Encadeada][22] | C/C++ | Java | [Python](/src/python/lista_encadeada.py) | Go | Ruby | [Javascript](/src/javascript/ListaSimplesmenteEncadeada.js) | Pascal | +| [Lista Duplamente Encadeada][23] | [C/C++](/src/c/ListaDuplamenteEncadeada.c) | [Java](/src/java/ListaDuplamenteEncadeada.java) | [Python](/src/python/lista_duplamente_encadeada.py) | Go | Ruby | [Javascript](/src/javascript/ListaDumplamenteEncadeada.js) | Pascal | | [Lista Ligada Não Ordenada][24] | [C/C++](/src/c/ListaLigadaNaoOrdenada.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| Lista Sequencial Ordenada | [C/C++](/src/c/ListaSequencialOrdenada.c) | Java | [Python](/src/python/ListaSequencialOrdenada.py) | Go | Ruby | Javascript | Pascal | +| Lista Sequencial Ordenada | [C/C++](/src/c/ListaSequencialOrdenada.c) | Java | [Python](/src/python/lista_sequencial_ordenada.py) | Go | Ruby | Javascript | Pascal | | [Pilha][31] | [C/C++](/src/c/Pilha.c) | [Java](/src/java/Pilha.java) | [Python](/src/python/pilha.py) | Go | [Ruby](/src/ruby/Pilha.rb) | [Javascript](/src/javascript/Pilha.js) | [Pascal](/src/pascal/pilha.pas) | | Pilha Ligada Dinâmica | [C/C++](/src/c/PilhaLigadaDinamica.c) | Java | Python | Go | Ruby | Javascript | Pascal | @@ -55,22 +55,22 @@ Com o objetivo de alcançar uma abrangência maior e encorajar novas pessoas a c | [Comb Sort][38] | C/C++ | Java | Python | [Go](/src/go/combsort/combsort.go) | Ruby | [Javascript](/src/javascript/CombSort.js) | Pascal | | [Counting Sort][39] | C/C++ | Java | Python | [Go](/src/go/countingsort/countingsort.go) | [Ruby](/src/ruby/count_sort.rb) | Javascript | Pascal | | [Gnome Sort][40] | C/C++ | Java | Python | [Go](/src/go/gnomesort/gnomesort.go) | Ruby | Javascript | Pascal | -| [Heapsort][41] | C/C++ | [Java](/src/java/HeapSort.java) | Python | [Go](/src/go/heapsort/heapsort.go) | [Ruby](/src/ruby/heap_sort.rb) | Javascript | [Pascal](/src/pascal/heapsort.pas) | -| [Insertion Sort][42] | [C/C++](/src/c/InsertionSort.cpp) | [Java](/src/java/InsertionSort.java) | [Python](/src/python/InsertionSortIterativo.py) | [Go](/src/go/insertionsort/insertionsort.go) | [Ruby](/src/ruby/insertion_sort.rb) | [Javascript](/src/javascript/InsertionSort.js) | Pascal | -| Insertion Sort Recursivo | C/C++ | Java | [Python](/src/python/InsertionSortRecursivo.py) | Go | Ruby | Javascript | Pascal | +| [Heapsort][41] | C/C++ | [Java](/src/java/HeapSort.java) | Python | [Go](/src/go/heapsort/heap_sort.go) | [Ruby](/src/ruby/heap_sort.rb) | Javascript | [Pascal](/src/pascal/heapsort.pas) | +| [Insertion Sort][42] | [C/C++](/src/c/InsertionSort.cpp) | [Java](/src/java/InsertionSort.java) | [Python](/src/python/insertion_sort_iterativo.py) | [Go](/src/go/insertionsort/insertionsort.go) | [Ruby](/src/ruby/insertion_sort.rb) | [Javascript](/src/javascript/InsertionSort.js) | Pascal | +| Insertion Sort Recursivo | C/C++ | Java | [Python](/src/python/insertion_sort_recursivo.py) | Go | Ruby | Javascript | Pascal | | [Merge Sort][44] | [C/C++](/src/c/MergeSort.c) | [Java](/src/java/Mergesort.java) | Python | [Go](/src/go/mergesort/mergesort.go) | [Ruby](/src/ruby/merge_sort.rb) | [Javascript](/src/javascript/MergeSort.js) | [Pascal](/src/pascal/sort/mergesort.pas) | -| [Quicksort][45] | [C/C++](/src/c/QuickSort.cpp) | [Java](/src/java/Quicksort.java) | [Python](/src/python/QuickSort.py) | [Go](/src/go/quicksort/quicksort.go) | [Ruby](/src/ruby/quick_sort.rb) | [Javascript](/src/javascript/QuickSort.js) | Pascal | +| [Quicksort][45] | [C/C++](/src/c/QuickSort.cpp) | [Java](/src/java/Quicksort.java) | [Python](/src/python/quick_sort.py) | [Go](/src/go/quicksort/quicksort.go) | [Ruby](/src/ruby/quick_sort.rb) | [Javascript](/src/javascript/QuickSort.js) | Pascal | | [Radix Sort][46] | C/C++ | [Java](/src/java/RadixSort.java) | Python | [Go](/src/go/radixsort/radixsort.go) | [Ruby](/src/ruby/radix_sort.rb) | Javascript | Pascal | -| [Selection Sort][47] | [C/C++](/src/c/SelectionSort.cpp) | [Java](/src/java/SelectionSort.java) | [Python](/src/python/SelectionSort.py) | [Go](/src/go/selectionsort/selectionsort.go) | [Ruby](/src/ruby/selection_sort.rb) | [Javascript](/src/javascript/SelectionSort.js) | [Pascal](/src/pascal/selectsort.pas) | -| [Shell Sort][48] | C/C++ | [Java](/src/java/ShellSort.java) | [Python](/src/python/shellSort.py) | [Go](/src/go/shellsort/shellsort.go) | Ruby | [Javascript](/src/javascript/ShellSort.js) | Pascal | -| [Timsort][53] | C/C++ | Java | [Python](/src/python/timsort.py) | Go | Ruby | Javascript | Pascal | +| [Selection Sort][47] | [C/C++](/src/c/SelectionSort.cpp) | [Java](/src/java/SelectionSort.java) | [Python](/src/python/selection_sort.py) | [Go](/src/go/selectionsort/selectionsort.go) | [Ruby](/src/ruby/selection_sort.rb) | [Javascript](/src/javascript/SelectionSort.js) | [Pascal](/src/pascal/selectsort.pas) | +| [Shell Sort][48] | C/C++ | [Java](/src/java/ShellSort.java) | [Python](/src/python/shell_sort.py) | [Go](/src/go/shellsort/shellsort.go) | Ruby | [Javascript](/src/javascript/ShellSort.js) | Pascal | +| [Timsort][53] | C/C++ | Java | [Python](/src/python/tim_sort.py) | Go | Ruby | Javascript | Pascal | | Extras | C/C++ | Java | Python | Go | Ruby | Javascript | Pascal | |-------------------------------------|-------|------|--------|----|------|------------|--------| -| Lista com 2 Pilhas | C/C++ | Java | [Python](/src/python/ListaComPilhas.py) | Go | Ruby | Javascript | Pascal | -| Problema da Soma de 2 Números | C/C++ | Java | [Python](/src/python/Soma2Numeros.py) | Go | Ruby | Javascript | Pascal | +| Lista com 2 Pilhas | C/C++ | Java | [Python](/src/python/lista_com_pilhas.py) | Go | Ruby | Javascript | Pascal | +| Problema da Soma de 2 Números | C/C++ | Java | [Python](/src/python/soma_dois_numeros.py) | Go | Ruby | Javascript | Pascal | | [Palíndromo][49] | [C/C++](/src/c/Palindromo.c) | Java | Python | Go | Ruby | Javascript | Pascal | -| Lista Encadeada Desordenada | C/C++ | Java | [Python](/src/python/ListaEncadeadaDesordenada.py) | Go | Ruby | Javascript | Pascal | +| Lista Encadeada Desordenada | C/C++ | Java | [Python](/src/python/lista_encadeada_desordenada.py) | Go | Ruby | Javascript | Pascal | | [Calcula o PI (Fórmula de Leibniz)][50] | C/C++ | Java | [Python](/src/python/calculate_pi.py) | Go | Ruby | Javascript | Pascal | | Busca em Labirinto | C/C++ | Java | [Python](/src/python/busca_em_labirinto.py) | Go | Ruby | Javascript | Pascal | From 476b38dc48c977f6aefa82c9632e5a6fbea0eec6 Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Sun, 24 May 2020 11:57:51 -0300 Subject: [PATCH 6/8] removes wrong indentation --- src/python/busca_sentinela.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/python/busca_sentinela.py b/src/python/busca_sentinela.py index 38f36e00..f5ab3f34 100644 --- a/src/python/busca_sentinela.py +++ b/src/python/busca_sentinela.py @@ -1,20 +1,20 @@ -""" Implementação do algoritmo de busca sentinela """ +""" Implementacao do algoritmo de busca sentinela """ def busca_sentinela(list_to_search, value): """ - Implementação de um algoritmo de busca sentinela. + Implementacao de um algoritmo de busca sentinela. Argumentos: value: Any. Valor a ser buscado na lista - list_to_search: list. lista na qual o valor será buscado + list_to_search: list. lista na qual o valor sera buscado - Retorna o índice do valor em "list_to_search" ou -1 caso não exista nela. + Retorna o indice do valor em "list_to_search" ou -1 caso nao exista nela. """ list_to_search.append(value) list_index = 0 while list_to_search[list_index] != value: list_index = list_index + 1 - list_to_search.pop() + list_to_search.pop() if list_index == len(list_to_search): return -1 return list_index From 226a394cbf0451b3348eb9b721d516616c4340b7 Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Sun, 24 May 2020 11:58:49 -0300 Subject: [PATCH 7/8] removes wrong indentation --- src/python/lista_sequencial_ordenada.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/python/lista_sequencial_ordenada.py b/src/python/lista_sequencial_ordenada.py index fd875272..c846d03c 100644 --- a/src/python/lista_sequencial_ordenada.py +++ b/src/python/lista_sequencial_ordenada.py @@ -12,7 +12,7 @@ def inserir_lista(chave, lista): i, p = 0, 0 while lista[i] < chave: i += 1 - p = len(lista) - 2 + p = len(lista) - 2 while p >= i: lista[p+1] = lista[p] p -= 1 From 2ff68c45912e28b75d35f9ec269a9ccb2a85313c Mon Sep 17 00:00:00 2001 From: Lucas Silva Date: Sun, 24 May 2020 12:00:30 -0300 Subject: [PATCH 8/8] adds indentation --- src/python/shell_sort.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/python/shell_sort.py b/src/python/shell_sort.py index 8d2a3036..ad14d09b 100644 --- a/src/python/shell_sort.py +++ b/src/python/shell_sort.py @@ -1,11 +1,11 @@ -""" Implementaçao do algoritmo shell sort """ +""" Implementacao do algoritmo shell sort """ def shell_sort(a_list): """ Algoritmo shell sort. Argumentos: - a_list: list. Uma lista não ordenada + a_list: list. Uma lista nao ordenada """ sublist_count = len(a_list)//2 while sublist_count > 0: @@ -21,11 +21,11 @@ def gap_insertion_sort(a_list, start, gap): for i in range(start+gap, len(a_list), gap): current_value = a_list[i] position = i - while position >= gap and a_list[position-gap] > current_value: - a_list[position] = a_list[position - gap] - position = position - gap + while position >= gap and a_list[position-gap] > current_value: + a_list[position] = a_list[position - gap] + position = position - gap - a_list[position] = current_value + a_list[position] = current_value some_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] shell_sort(some_list) @@ -33,10 +33,10 @@ def gap_insertion_sort(a_list, start, gap): def shell(seq): """ - Algoritmo de ordenação shell + Algoritmo de ordenacao shell Argumentos: - seq: list. lista não ordenada + seq: list. lista nao ordenada """ inc = len(seq) // 2 while inc: