Skip to content

Commit

Permalink
Merge pull request #343 from lcgabaldon/python_eng_translations
Browse files Browse the repository at this point in the history
Translated Python algorithms and comments to English.
  • Loading branch information
kelvins authored Mar 11, 2024
2 parents d6f8f59 + f46e72e commit f4d053b
Show file tree
Hide file tree
Showing 19 changed files with 240 additions and 239 deletions.
40 changes: 20 additions & 20 deletions src/python/binary_search.py
Original file line number Diff line number Diff line change
@@ -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))
4 changes: 1 addition & 3 deletions src/python/binary_search_tree.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Arvore Binaria de Busca em Python
"""
""" Binary Search Tree in Python """


class TreeNode:
Expand Down
2 changes: 1 addition & 1 deletion src/python/binary_tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" Implementação de uma árvore binária """
""" Binary Tree in Python """


class Node:
Expand Down
4 changes: 2 additions & 2 deletions src/python/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" Implementation of the bubble sort algorithm with recursion """
""" Recursive Bubble Sort in Python """


def bubble_sort(data, size):
Expand All @@ -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):
Expand Down
8 changes: 4 additions & 4 deletions src/python/calculate_pi.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/python/circular_linked_list.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" implementação de uma lista encadeada circular """
""" Implementation of a circular linked list in Python """

import unittest

Expand Down
16 changes: 6 additions & 10 deletions src/python/comb_sort.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)}")
30 changes: 15 additions & 15 deletions src/python/counting_sort.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
# 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

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}")
167 changes: 81 additions & 86 deletions src/python/doubly_linked_list.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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()
Loading

0 comments on commit f4d053b

Please sign in to comment.