diff --git a/src/python/binary_search.py b/src/python/binary_search.py index b85e4262..acfc880c 100644 --- a/src/python/binary_search.py +++ b/src/python/binary_search.py @@ -1,30 +1,30 @@ -""" Implementação do algoritmo de busca binária com recursão """ +""" Recursive Binary Search Algorithm in Python """ -def busca_binaria(valor, vetor, esquerda, direita): +def binary_search(value, vector, left, right): """ - Implementação de um algoritmo de busca binária com recursão. + Implementation of a binary search algorithm with recursion. - 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 + Arguments: + value: Any. Value to be searched for in the list + vector: List. Ordered list in which value will be searched for + left: Any. Leftmost index for binary search + right: Any. Rightmost index for binary search - Retorna o índice do valor em "vetor" ou -1 caso não exista nela. + Returns the index of value in vector; returns -1 if value not found in vector """ - meio = int((esquerda + direita) / 2) + middle = int((left + right) / 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 + if left <= right: + if value > vector[middle]: + left = middle + 1 + return binary_search(value, vector, left, right) + elif value < vector[middle]: + right = middle - 1 + return binary_search(value, vector, left, right) + return middle return -1 -lista = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] -print(busca_binaria(12, lista, 0, len(lista) - 1)) +list = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12] +print(binary_search(12, list, 0, len(list) - 1)) diff --git a/src/python/binary_search_tree.py b/src/python/binary_search_tree.py index 6cdfc481..2b7fa910 100644 --- a/src/python/binary_search_tree.py +++ b/src/python/binary_search_tree.py @@ -1,6 +1,4 @@ -""" -Arvore Binaria de Busca em Python -""" +""" Binary Search Tree in Python """ class TreeNode: diff --git a/src/python/binary_tree.py b/src/python/binary_tree.py index 8945200a..ede3fa47 100644 --- a/src/python/binary_tree.py +++ b/src/python/binary_tree.py @@ -1,4 +1,4 @@ -""" Implementação de uma árvore binária """ +""" Binary Tree in Python """ class Node: diff --git a/src/python/bubble_sort.py b/src/python/bubble_sort.py index 232e310a..7730f855 100755 --- a/src/python/bubble_sort.py +++ b/src/python/bubble_sort.py @@ -1,4 +1,4 @@ -""" Implementation of the bubble sort algorithm with recursion """ +""" Recursive Bubble Sort in Python """ def bubble_sort(data, size): @@ -9,7 +9,7 @@ def bubble_sort(data, size): data: list. List to be sorted size: int. List size - Returns the ordered "date" list. + Returns the ordered "data" list. """ swap = False for i in range(0, size - 1): diff --git a/src/python/calculate_pi.py b/src/python/calculate_pi.py index 00892776..9a7ae1b4 100644 --- a/src/python/calculate_pi.py +++ b/src/python/calculate_pi.py @@ -1,14 +1,14 @@ -""" Implementaço de um algoritmo de cálculo do PI """ +""" Calculating PI in Python """ def calculate_pi(number): """ - Implementação de um algoritmo de cálculo do PI. + Implementation of a PI calculation algorithm. - Argumentos: + Arguments: number: int. - Retorna o valor de PI. + Returns the value of PI. """ denominator = 1.0 operation = 1.0 diff --git a/src/python/circular_linked_list.py b/src/python/circular_linked_list.py index f4806b83..a65b2f61 100644 --- a/src/python/circular_linked_list.py +++ b/src/python/circular_linked_list.py @@ -1,4 +1,4 @@ -""" implementação de uma lista encadeada circular """ +""" Implementation of a circular linked list in Python """ import unittest diff --git a/src/python/comb_sort.py b/src/python/comb_sort.py index 01a5810c..8adde32f 100644 --- a/src/python/comb_sort.py +++ b/src/python/comb_sort.py @@ -1,13 +1,9 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# ---------------------------------------------------------------------------- -# Created By : octaviolage -# Created Date: 2022-05-15 -# version ='1.0' -# ------------------------------- +""" Comb Sort in Python """ + + def comb_sort(arr: list) -> list: """ - Implementação de um algoritmo de ordenação combinada. + Implementation of comb sort algorithm """ gap = len(arr) shrink = 1.3 @@ -28,5 +24,5 @@ def comb_sort(arr: list) -> list: from random import randint my_list = [randint(0, 100) for _ in range(10)] - print(f"Lista: {my_list}") - print(f"Ordenada: {comb_sort(my_list)}") + print(f"List: {my_list}") + print(f"Sorted list: {comb_sort(my_list)}") diff --git a/src/python/counting_sort.py b/src/python/counting_sort.py index a113be1e..fec1bae6 100644 --- a/src/python/counting_sort.py +++ b/src/python/counting_sort.py @@ -1,27 +1,27 @@ -# Algoritmo de ordenação Counting sort em Python +""" Counting sort in Python """ import random def counting_sort(arr): - # Encontra o maior elemento na lista + """Finding the max element in the list""" k = max(arr) + 1 - # Inicializa o array de contagem com zeros + """ Initialing count array of len k with 0's """ count = [0] * k - # Conta a frequência de cada elemento + """ Counts frequency of each element """ for i in arr: count[i] += 1 - # Atualiza o array de contagem para refletir a posição correta de cada elemento na lista ordenada + """ Updates count array to reflect the correct position of each element in the sorted list """ for i in range(1, k): count[i] += count[i - 1] - # Inicializa o array de resultado com zeros + """ Initializing result list with 0's """ result = [0] * len(arr) - # Preenche o array de resultado com os elementos ordenados + """ Fill result array with the sorted elements""" for i in reversed(arr): result[count[i] - 1] = i count[i] -= 1 @@ -29,15 +29,15 @@ def counting_sort(arr): return result -# Gera uma lista de n números aleatórios +""" Generate a list of n random integers """ n = 10 -lista = [random.randint(0, 100) for _ in range(n)] +list = [random.randint(0, 100) for _ in range(n)] -# Imprime a lista original sem ordenação -print(f"Lista Original: {lista}") +""" Prints original, unsorted list""" +print(f"List: {list}") -# Ordena a lista utilizando o algoritmo de Counting Sort -lista_ordenada = counting_sort(lista) +""" Sorts list using counting sort algorithm """ +sorted_list = counting_sort(list) -# Imprime a lista ordenada -print(f"Lista Ordenada: {lista_ordenada}") +""" Prints sorted list """ +print(f"Sorted list: {sorted_list}") diff --git a/src/python/doubly_linked_list.py b/src/python/doubly_linked_list.py index 7b800113..1f4b73d7 100644 --- a/src/python/doubly_linked_list.py +++ b/src/python/doubly_linked_list.py @@ -1,8 +1,8 @@ """ -Lista Duplamente Encadeada +Doubly Linked List -A cabeca da lista sempre 'aponta' para o primeiro no -O rabo da lista sempre 'aponta' para o ultimo no +The 'head' of the list always points to the first node +The 'tail' of the list always points to the final node None <--- | 2 | ---> None None <--- | 2 | <---> | 5 | ---> None @@ -11,102 +11,97 @@ """ -class No: - def __init__(self, dado, anterior, proximo): - self.dado = dado - self.anterior = anterior - self.proximo = proximo +class Node: + def __init__(self, data, prev, next): + self.data = data + self.prev = prev + self.next = next -class ListaDuplamenteEncadeada: - cabeca = None - rabo = None +class DoublyLinkedList: + head = None + tail = None - def acrescentar(self, dado): - """Acrescenta um novo no a lista.""" - # Cria um novo no apontando para None (anterior e proximo) - novo_no = No(dado, None, None) + def append(self, data): + # Creates a new node pointing to None (prev and next) + new_node = Node(data, None, None) - # Se a cabeca eh None a lista esta vazia - # Tanto a cabeca quanto o rabo recebem o novo no - if self.cabeca is None: - self.cabeca = novo_no - self.rabo = novo_no - # Caso contrario, se ja existir algum valor na lista + # If the list is empty, both head and tail point to the new node + if self.head is None: + self.head = new_node + self.tail = new_node else: - # O anterior 'aponta' para o rabo (ultimo no adicionado) - novo_no.anterior = self.rabo - # O proximo sempre aponta para None - novo_no.proximo = None - # O proximo do rabo sempre aponta para o novo no - 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: + # For a non-empty list, adjust pointers to add the new node at the end + new_node.prev = self.tail # New node's prev points to the current tail + self.tail.next = new_node # Current tail's next points to the new node + self.tail = new_node # Update tail to be the new node + + # No additional 'new_node.next = None' is needed as it's already None by default + + def delete(self, data): + """Deletes a node from the list""" + """ Current node is first node in the list""" + curr_node = self.head + + # We search for the data we want to delete + # While current node is not invalid + while curr_node is not None: # Verifica se eh o dado que estamos buscando - if no_atual.dado == dado: - # Se o dado que estamos buscando esta no primeiro no - # da lista, nao temos anterior - if no_atual.anterior is None: - # A cabeca 'aponta' para o proximo no da lista - self.cabeca = no_atual.proximo - # E o anterior do proximo no aponta para None - no_atual.proximo.anterior = None + if curr_node.data == data: + # If data we are looking for is in first node + # If we do not have a previous node in the list + if curr_node.prev is None: + # Head points to next node in the list + self.head = curr_node.next + # And the previous of the next node does not point to None + curr_node.next.prev = None else: - # Exemplo: Removendo o valor 5 + # Example: Deleting the value 5 # ... <---> | 2 | <---> | 5 | <---> | 12 | <---> ... # - # O proximo do valor 2 passa a apontar para o 12 e - # o anterior do valor 12 passa a apontar para o 2 + # Next node of 2 will now point to 12 instead of 5 + # Previous node of 12 will not point to 2 instead of 5 # --------------- # ... <---> | 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:") - - # O no atual eh o primeiro no da lista - no_atual = self.cabeca - - no = "" - # Para cada no valido da lista - while no_atual is not None: - if no_atual.anterior is None: - no += "None " - no += "<---> | " + str(no_atual.dado) + " | " - if no_atual.proximo is None: - no += "<---> None" - - no_atual = no_atual.proximo - print(no) + curr_node.prev.next = curr_node.next + curr_node.next.prev = curr_node.prev + + # If current node does not hold desired data, move to next node + curr_node = curr_node.next + + def display(self): + """Displays all data in the list""" + print("Doubly Linked List: ") + + # Current node is head of the list + curr_node = self.head + + node = "" + # For each valid node in the list + while curr_node is not None: + if curr_node.prev is None: + node += "None " + node += "<---> | " + str(curr_node.data) + " | " + if curr_node.next is None: + node += "<---> None" + + curr_node = curr_node.next + print(node) print("=" * 80) -lista = ListaDuplamenteEncadeada() +list = DoublyLinkedList() -lista.acrescentar(2) -lista.mostrar() -lista.acrescentar(5) -lista.mostrar() -lista.acrescentar(12) -lista.mostrar() -lista.acrescentar(20) -lista.mostrar() +list.append(2) +list.display() +list.append(5) +list.display() +list.append(12) +list.display() +list.append(20) +list.display() -lista.remover(12) -lista.mostrar() -lista.remover(5) -lista.mostrar() +list.delete(12) +list.display() +list.delete(5) +list.display() diff --git a/src/python/exponentiation.py b/src/python/exponentiation.py index 17cf2d91..e54f9f38 100644 --- a/src/python/exponentiation.py +++ b/src/python/exponentiation.py @@ -1,21 +1,22 @@ -""" Algoritmo de exponenciação """ +""" Iterative exponentiation algorithm """ -def exponenciacao(base, expoente): +def exponentiation(base, exponent): """ - Implementação de um algoritmo de exponenciação. + Implementation of an exponentiation algorithm. - Argumentos: - base: int. Base da operação - expoente: int. Expoente da operação. + Arguments: + base (int): Base of operation + exponent (int): Exponent of operation - Retorna o resultado da operação de exponenciação + Returns: + Returns the result of the exponentiation operation. """ result = base - for _ in range(0, expoente - 1): + for _ in range(0, exponent - 1): result *= base return result -print(exponenciacao(5, 2)) -print(exponenciacao(5, 5)) +print(exponentiation(5, 2)) +print(exponentiation(5, 5)) diff --git a/src/python/exponentiation_recursive.py b/src/python/exponentiation_recursive.py index d38aacda..1db76fd2 100644 --- a/src/python/exponentiation_recursive.py +++ b/src/python/exponentiation_recursive.py @@ -1,22 +1,23 @@ -""" Algoritmo de exponenciação implementado com recursão. """ +""" Recursive exponentiation algorithm """ -def exponenciacao_recursiva(base, expoente): - """Implementação de um algoritmo de exponenciação. +def exponentiation_recursive(base, exponent): + """ + Implementation of an exponentiation algorithm using recursion. - Args: - base (int): Base da operação - expoente (int): Expoente da operação + Arguments: + base (int): Base of operation + exponent (int): Exponent of operation Returns: - Retorna o resultado da operaçao de exponenciação. + Returns the result of the exponentiation operation. """ - if expoente == 0: + if exponent == 0: return 1 - return base * exponenciacao_recursiva(base, expoente - 1) + return base * exponentiation_recursive(base, exponent - 1) if __name__ == "__main__": - print(exponenciacao_recursiva(5, 2)) - print(exponenciacao_recursiva(5, 5)) + print(exponentiation_recursive(5, 2)) + print(exponentiation_recursive(5, 5)) diff --git a/src/python/factorial.py b/src/python/factorial.py index 31146ba8..48ef04c4 100644 --- a/src/python/factorial.py +++ b/src/python/factorial.py @@ -1,14 +1,14 @@ -""" Uma implementação simples de um algoritmo fatorial """ +""" Iterative factorial algorithm """ -def fatorial(num): +def factorial(num): """ - Uma implementação simples de um algoritmo de fatorial. + Implementation of the factorial algorithm iteratively. - Argumentos: - num: int. o número do qual deseja-se obter o fatorial. + Arguments: + num: int. the number of which you want to obtain the factorial. - Retorna o resultado da operação. + Returns the result of the factorial operation """ aux = 1 for i in range(2, num + 1): @@ -17,4 +17,4 @@ def fatorial(num): if __name__ == "__main__": - print(fatorial(5)) + print(factorial(5)) diff --git a/src/python/factorial_recursive.py b/src/python/factorial_recursive.py index cec8de56..d497d22d 100644 --- a/src/python/factorial_recursive.py +++ b/src/python/factorial_recursive.py @@ -1,19 +1,19 @@ -""" Algoritmo de fatorial implementado com recursão """ +""" Recursive factorial algorithm """ -def fatorial_recursivo(numero): +def factorial_recursive(num): """ - Implementação de um algoritmo de fatorial com recursão. + Implementation of factorial algorithm using recursion - Argumentos: - numero: int. o número do qual deseja-se obter o fatorial. + Arguments: + num: int. the number of which you want to obtain the factorial. - Retorna o resultado da operação. + Returns the result of the factorial operation """ - if numero == 1: + if num == 1: return 1 - return numero * fatorial_recursivo(numero - 1) + return num * factorial_recursive(num - 1) -print(fatorial_recursivo(5)) +print(factorial_recursive(5)) diff --git a/src/python/fibonacci_iterative.py b/src/python/fibonacci_iterative.py index 2df05079..f394c049 100755 --- a/src/python/fibonacci_iterative.py +++ b/src/python/fibonacci_iterative.py @@ -1,8 +1,8 @@ """ -Implementaço de vários algoritmos Fibonacci +Iterative Fibonacci Algorithm -A lib "time" foi utilizada para marcar o tempo de -execução dos algoritmos em segundos +The lib "time" was used to mark the time of +execution of algorithms in seconds """ import functools @@ -20,13 +20,13 @@ def fibonacci(number): def main(name, func, number=35): """ - Roda o algoritmo e mostra o tempo de execução dele + Run iterative algorithm and show its execution time """ start_time = time.time() result = func(number) diff_time = time.time() - start_time - print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos") + print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") if __name__ == "__main__": - main("Iterativa", fibonacci) + main("Iterative", fibonacci) diff --git a/src/python/fibonacci_memoization.py b/src/python/fibonacci_memoization.py index 1ff01958..1a8c8e6e 100644 --- a/src/python/fibonacci_memoization.py +++ b/src/python/fibonacci_memoization.py @@ -1,10 +1,16 @@ +""" +Recursive Fibonacci Algorithm using a Cache +""" + import functools import time @functools.lru_cache(maxsize=None) def fibonacci(number): - """Fibonacci recursiva com cache.""" + """ + Recursive fibonacci algorithm with cache + """ if number < 2: return number return fibonacci(number - 1) + fibonacci(number - 2) @@ -12,13 +18,13 @@ def fibonacci(number): def main(name, func, number=35): """ - Roda o algoritmo e mostra o tempo de execução dele + Run algorithm and show its execution time """ start_time = time.time() result = func(number) diff_time = time.time() - start_time - print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos") + print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") if __name__ == "__main__": - main("Fibonacci Memoization:", fibonacci) + main("Memorization:", fibonacci) diff --git a/src/python/fibonacci_recursive.py b/src/python/fibonacci_recursive.py index 1bbba363..106d7f36 100644 --- a/src/python/fibonacci_recursive.py +++ b/src/python/fibonacci_recursive.py @@ -1,15 +1,18 @@ """ -Implementaço de vários algoritmos Fibonacci +Recursive Fibonacci Algorithm -A lib "time" foi utilizada para marcar o tempo de -execução dos algoritmos em segundos +The lib "time" was used to mark the time of +execution of algorithms in seconds """ import time def fibonacci(number): - """Fibonnaci recursiva.""" + """ + Recursive Fibonacci + """ + if number < 2: return number return fibonacci(number - 1) + fibonacci(number - 2) @@ -17,13 +20,13 @@ def fibonacci(number): def main(name, func, number=35): """ - Roda o algoritmo e mostra o tempo de execução dele + Run the algorithm and show its execution time """ start_time = time.time() result = func(number) diff_time = time.time() - start_time - print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "segundos") + print("Fibonacci", name, ":", result, ":", "%.8f" % diff_time, "seconds") if __name__ == "__main__": - main("Recursiva", fibonacci) + main("Recursive", fibonacci) diff --git a/src/python/insertion_sort.py b/src/python/insertion_sort.py index 431972e1..b97eef95 100644 --- a/src/python/insertion_sort.py +++ b/src/python/insertion_sort.py @@ -1,59 +1,63 @@ -"""Implementação do algoritmo insertion sort iterativo e recursivo.""" +""" Insertion Sort in Python (Iterative and Recursive) """ -def insertion_sort_iterativo(vetor): +def insertion_sort_iterative(vector): """ - Implementação do algoritmo de insertion sort iterativo. + Implementation of insertion sort iteratively. - Args: - vetor (list): lista que será ordenada. + Arguments: + vector (list): list to be sorted. Returns: - Retorna a lista ordenada. + Returns the sorted list. """ - for i in range(1, len(vetor)): - chave = vetor[i] + for i in range(1, len(vector)): + key = vector[i] aux = i - 1 - while aux >= 0 and vetor[aux] > chave: - vetor[aux + 1] = vetor[aux] + while aux >= 0 and vector[aux] > key: + vector[aux + 1] = vector[aux] aux -= 1 - vetor[aux + 1] = chave - return vetor + vector[aux + 1] = key + return vector -def insertion_sort_recursivo(vetor, indice): +def insertion_sort_recursive(vector, index): """ - Implementação do algoritmo de insertion sort recursivo. + Implementation of insertion sort recursively. - Args: - vetor (list): lista que será ordenada. - indice (int): índice do elemento a ser ordenado na lista. + Arguments: + vector (list): list to be sorted. + index (int): index of the element to be sorted in the list. Returns: - Retorna a lista ordenada. + Returns the sorted list. """ - aux = indice - while vetor[aux] < vetor[aux - 1]: - temp = vetor[aux] - vetor[aux] = vetor[aux - 1] - vetor[aux - 1] = temp + aux = index + while vector[aux] < vector[aux - 1]: + temp = vector[aux] + vector[aux] = vector[aux - 1] + vector[aux - 1] = temp aux -= 1 if aux == 0: break - if indice < len(vetor) - 1: - insertion_sort_recursivo(vetor, indice + 1) - return vetor + if index < len(vector) - 1: + insertion_sort_recursive(vector, index + 1) + return vector if __name__ == "__main__": - lista_nao_ordenada = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] - print("Lista não ordenada:") - print(lista_nao_ordenada) + list1 = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] + print("Unsorted list: ") + print(list1) - lista_nao_ordenada = insertion_sort_iterativo(lista_nao_ordenada) - print("Lista ordenada com insertion sort iterativo:") - print(lista_nao_ordenada) + list1 = insertion_sort_iterative(list1) + print("Sorted list with iterative insertion sort: ") + print(list1) - lista_nao_ordenada = insertion_sort_recursivo(lista_nao_ordenada, 1) - print("Lista ordenada com insertion sort recursivo:") - print(lista_nao_ordenada) + list2 = [8, 1, 3, 5, 7, 9, 0, 2, 4, 6] + print("Unsorted list: ") + print(list2) + + list2 = insertion_sort_recursive(list2, 1) + print("Sorted list with recursive insertion sort: ") + print(list2) diff --git a/src/python/quick_sort.py b/src/python/quick_sort.py index 7c1dd5bd..a1015cdd 100644 --- a/src/python/quick_sort.py +++ b/src/python/quick_sort.py @@ -1,15 +1,15 @@ -""" Implementaçao do algoritmo quick sort """ +""" Quick Sort in Python """ def swap(a_list, pos1, pos2): - """Troca a posição de dois itens em uma lista""" + """Swaps the position of two items in a list""" temp = a_list[pos1] a_list[pos1] = a_list[pos2] a_list[pos2] = temp def partition(a_list, start, end): - """Divide uma lista""" + """Splits a list""" pivot = a_list[start] while True: while a_list[start] < pivot: @@ -28,7 +28,7 @@ def partition(a_list, start, end): def quick_sort(a_list, start, end): - """Algoritmo de quick sort""" + """Quick sort algorithm""" if start < end: part = partition(a_list, start, end) quick_sort(a_list, start, part) diff --git a/src/python/singly_linked_list.py b/src/python/singly_linked_list.py index fed7cf5c..482d3037 100644 --- a/src/python/singly_linked_list.py +++ b/src/python/singly_linked_list.py @@ -1,8 +1,5 @@ """ -!/usr/bin/env python --*- coding: utf-8 -*- - -Lista Ligada: +Linked List: _________ _________ _________ _________ head --> | 2 | --|--> | 1 | --|--> | 5 | --|--> | 3 | --|--> None --------- --------- --------- ---------