Skip to content

Commit 92167dc

Browse files
committed
Translated code and comments in each of the files.
1 parent d6f8f59 commit 92167dc

19 files changed

+244
-242
lines changed

Diff for: src/python/binary_search.py

+20-20
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
1-
""" Implementação do algoritmo de busca binária com recursão """
1+
""" Recursive Binary Search Algorithm in Python """
22

33

4-
def busca_binaria(valor, vetor, esquerda, direita):
4+
def binary_search(value, vector, left, right):
55
"""
6-
Implementação de um algoritmo de busca binária com recursão.
6+
Implementation of a binary search algorithm with recursion.
77
8-
Argumentos:
9-
valor: Any. Valor a ser buscado na lista
10-
vetor: list. lista ordenada na qual o valor será buscado
11-
esquerda: Any. Valor inicial da metade buscada
12-
direita: Any. Valor final da metade buscada
8+
Arguments:
9+
value: Any. Value to be searched for in the list
10+
vector: List. Ordered list in which value will be searched for
11+
left: Any. Leftmost index for binary search
12+
right: Any. Rightmost index for binary search
1313
14-
Retorna o índice do valor em "vetor" ou -1 caso não exista nela.
14+
Returns the index of value in vector; returns -1 if value not found in vector
1515
"""
16-
meio = int((esquerda + direita) / 2)
16+
middle = int((left + right) / 2)
1717

18-
if esquerda <= direita:
19-
if valor > vetor[meio]:
20-
esquerda = meio + 1
21-
return busca_binaria(valor, vetor, esquerda, direita)
22-
elif valor < vetor[meio]:
23-
direita = meio - 1
24-
return busca_binaria(valor, vetor, esquerda, direita)
25-
return meio
18+
if left <= right:
19+
if value > vector[middle]:
20+
left = middle + 1
21+
return binary_search(value, vector, left, right)
22+
elif value < vector[middle]:
23+
right = middle - 1
24+
return binary_search(value, vector, left, right)
25+
return middle
2626
return -1
2727

2828

29-
lista = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12]
30-
print(busca_binaria(12, lista, 0, len(lista) - 1))
29+
list = [0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12]
30+
print(binary_search(12, list, 0, len(list) - 1))

Diff for: src/python/binary_search_tree.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
"""
2-
Arvore Binaria de Busca em Python
3-
"""
1+
""" Binary Search Tree in Python """
42

53

64
class TreeNode:

Diff for: src/python/binary_tree.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Implementação de uma árvore binária """
1+
""" Binary Tree in Python """
22

33

44
class Node:

Diff for: src/python/bubble_sort.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Implementation of the bubble sort algorithm with recursion """
1+
""" Recursive Bubble Sort in Python """
22

33

44
def bubble_sort(data, size):
@@ -9,7 +9,7 @@ def bubble_sort(data, size):
99
data: list. List to be sorted
1010
size: int. List size
1111
12-
Returns the ordered "date" list.
12+
Returns the ordered "data" list.
1313
"""
1414
swap = False
1515
for i in range(0, size - 1):

Diff for: src/python/calculate_pi.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
""" Implementaço de um algoritmo de cálculo do PI """
1+
""" Calculating PI in Python """
22

33

44
def calculate_pi(number):
55
"""
6-
Implementação de um algoritmo de cálculo do PI.
6+
Implementation of a PI calculation algorithm.
77
8-
Argumentos:
8+
Arguments:
99
number: int.
1010
11-
Retorna o valor de PI.
11+
Returns the value of PI.
1212
"""
1313
denominator = 1.0
1414
operation = 1.0

Diff for: src/python/circular_linked_list.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" implementação de uma lista encadeada circular """
1+
""" Implementation of a circular linked list in Python """
22

33
import unittest
44

Diff for: src/python/comb_sort.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
1-
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
3-
# ----------------------------------------------------------------------------
4-
# Created By : octaviolage
5-
# Created Date: 2022-05-15
6-
# version ='1.0'
7-
# -------------------------------
1+
""" Comb Sort in Python """
2+
3+
84
def comb_sort(arr: list) -> list:
95
"""
10-
Implementação de um algoritmo de ordenação combinada.
6+
Implementation of comb sort algorithm
117
"""
128
gap = len(arr)
139
shrink = 1.3
@@ -28,5 +24,5 @@ def comb_sort(arr: list) -> list:
2824
from random import randint
2925

3026
my_list = [randint(0, 100) for _ in range(10)]
31-
print(f"Lista: {my_list}")
32-
print(f"Ordenada: {comb_sort(my_list)}")
27+
print(f"List: {my_list}")
28+
print(f"Sorted list: {comb_sort(my_list)}")

Diff for: src/python/counting_sort.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,43 @@
1-
# Algoritmo de ordenação Counting sort em Python
1+
""" Counting sort in Python """
22

33
import random
44

55

66
def counting_sort(arr):
7-
# Encontra o maior elemento na lista
7+
""" Finding the max element in the list """
88
k = max(arr) + 1
99

10-
# Inicializa o array de contagem com zeros
10+
""" Initialing count array of len k with 0's """
1111
count = [0] * k
1212

13-
# Conta a frequência de cada elemento
13+
""" Counts frequency of each element """
1414
for i in arr:
1515
count[i] += 1
1616

17-
# Atualiza o array de contagem para refletir a posição correta de cada elemento na lista ordenada
17+
""" Updates count array to reflect the correct position of each element in the sorted list """
1818
for i in range(1, k):
1919
count[i] += count[i - 1]
2020

21-
# Inicializa o array de resultado com zeros
21+
""" Initializing result list with 0's """
2222
result = [0] * len(arr)
2323

24-
# Preenche o array de resultado com os elementos ordenados
24+
""" Fill result array with the sorted elements"""
2525
for i in reversed(arr):
2626
result[count[i] - 1] = i
2727
count[i] -= 1
2828

2929
return result
3030

3131

32-
# Gera uma lista de n números aleatórios
32+
""" Generate a list of n random integers """
3333
n = 10
34-
lista = [random.randint(0, 100) for _ in range(n)]
34+
list = [random.randint(0, 100) for _ in range(n)]
3535

36-
# Imprime a lista original sem ordenação
37-
print(f"Lista Original: {lista}")
36+
""" Prints original, unsorted list"""
37+
print(f"List: {list}")
3838

39-
# Ordena a lista utilizando o algoritmo de Counting Sort
40-
lista_ordenada = counting_sort(lista)
39+
""" Sorts list using counting sort algorithm """
40+
sorted_list = counting_sort(list)
4141

42-
# Imprime a lista ordenada
43-
print(f"Lista Ordenada: {lista_ordenada}")
42+
""" Prints sorted list """
43+
print(f"Sorted list: {sorted_list}")

Diff for: src/python/doubly_linked_list.py

+83-87
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
"""
2-
Lista Duplamente Encadeada
2+
Doubly Linked List
33
4-
A cabeca da lista sempre 'aponta' para o primeiro no
5-
O rabo da lista sempre 'aponta' para o ultimo no
4+
The 'head' of the list always points to the first node
5+
The 'tail' of the list always points to the final node
66
77
None <--- | 2 | ---> None
88
None <--- | 2 | <---> | 5 | ---> None
@@ -11,102 +11,98 @@
1111
"""
1212

1313

14-
class No:
15-
def __init__(self, dado, anterior, proximo):
16-
self.dado = dado
17-
self.anterior = anterior
18-
self.proximo = proximo
14+
class Node:
15+
def __init__(self, data, prev, next):
16+
self.data = data
17+
self.prev = prev
18+
self.next = next
1919

2020

21-
class ListaDuplamenteEncadeada:
22-
cabeca = None
23-
rabo = None
21+
class DoublyLinkedList:
22+
head = None
23+
tail = None
24+
25+
def append(self, data):
26+
# Creates a new node pointing to None (prev and next)
27+
new_node = Node(data, None, None)
2428

25-
def acrescentar(self, dado):
26-
"""Acrescenta um novo no a lista."""
27-
# Cria um novo no apontando para None (anterior e proximo)
28-
novo_no = No(dado, None, None)
29-
30-
# Se a cabeca eh None a lista esta vazia
31-
# Tanto a cabeca quanto o rabo recebem o novo no
32-
if self.cabeca is None:
33-
self.cabeca = novo_no
34-
self.rabo = novo_no
35-
# Caso contrario, se ja existir algum valor na lista
29+
# If the list is empty, both head and tail point to the new node
30+
if self.head is None:
31+
self.head = new_node
32+
self.tail = new_node
3633
else:
37-
# O anterior 'aponta' para o rabo (ultimo no adicionado)
38-
novo_no.anterior = self.rabo
39-
# O proximo sempre aponta para None
40-
novo_no.proximo = None
41-
# O proximo do rabo sempre aponta para o novo no
42-
self.rabo.proximo = novo_no
43-
# O rabo agora eh o novo no
44-
self.rabo = novo_no
45-
46-
def remover(self, dado):
47-
"""Remove um no da lista."""
48-
# O no atual eh o primeiro no da lista
49-
no_atual = self.cabeca
50-
51-
# Vamos procurar pelo dado que queremos remover
52-
# Equanto o no atual for valido
53-
while no_atual is not None:
34+
# For a non-empty list, adjust pointers to add the new node at the end
35+
new_node.prev = self.tail # New node's prev points to the current tail
36+
self.tail.next = new_node # Current tail's next points to the new node
37+
self.tail = new_node # Update tail to be the new node
38+
39+
# No additional 'new_node.next = None' is needed as it's already None by default
40+
41+
42+
def delete(self, data):
43+
""" Deletes a node from the list """
44+
""" Current node is first node in the list"""
45+
curr_node = self.head
46+
47+
# We search for the data we want to delete
48+
# While current node is not invalid
49+
while curr_node is not None:
5450
# Verifica se eh o dado que estamos buscando
55-
if no_atual.dado == dado:
56-
# Se o dado que estamos buscando esta no primeiro no
57-
# da lista, nao temos anterior
58-
if no_atual.anterior is None:
59-
# A cabeca 'aponta' para o proximo no da lista
60-
self.cabeca = no_atual.proximo
61-
# E o anterior do proximo no aponta para None
62-
no_atual.proximo.anterior = None
51+
if curr_node.data == data:
52+
# If data we are looking for is in first node
53+
# If we do not have a previous node in the list
54+
if curr_node.prev is None:
55+
# Head points to next node in the list
56+
self.head = curr_node.next
57+
# And the previous of the next node does not point to None
58+
curr_node.next.prev = None
6359
else:
64-
# Exemplo: Removendo o valor 5
60+
# Example: Deleting the value 5
6561
# ... <---> | 2 | <---> | 5 | <---> | 12 | <---> ...
6662
#
67-
# O proximo do valor 2 passa a apontar para o 12 e
68-
# o anterior do valor 12 passa a apontar para o 2
63+
# Next node of 2 will now point to 12 instead of 5
64+
# Previous node of 12 will not point to 2 instead of 5
6965
# ---------------
7066
# ... <---> | 2 | <---|--- | 5 | ---|---> | 12 | <---> ...
71-
no_atual.anterior.proximo = no_atual.proximo
72-
no_atual.proximo.anterior = no_atual.anterior
73-
74-
# Se nao eh o no que estamos buscando va para o proximo
75-
no_atual = no_atual.proximo
76-
77-
def mostrar(self):
78-
"""Mostra todos os dados da lista."""
79-
print("Lista Duplamente Encadeada:")
80-
81-
# O no atual eh o primeiro no da lista
82-
no_atual = self.cabeca
83-
84-
no = ""
85-
# Para cada no valido da lista
86-
while no_atual is not None:
87-
if no_atual.anterior is None:
88-
no += "None "
89-
no += "<---> | " + str(no_atual.dado) + " | "
90-
if no_atual.proximo is None:
91-
no += "<---> None"
92-
93-
no_atual = no_atual.proximo
94-
print(no)
67+
curr_node.prev.next = curr_node.next
68+
curr_node.next.prev = curr_node.prev
69+
70+
# If current node does not hold desired data, move to next node
71+
curr_node = curr_node.next
72+
73+
def display(self):
74+
""" Displays all data in the list"""
75+
print("Doubly Linked List: ")
76+
77+
# Current node is head of the list
78+
curr_node = self.head
79+
80+
node = ""
81+
# For each valid node in the list
82+
while curr_node is not None:
83+
if curr_node.prev is None:
84+
node += "None "
85+
node += "<---> | " + str(curr_node.data) + " | "
86+
if curr_node.next is None:
87+
node += "<---> None"
88+
89+
curr_node = curr_node.next
90+
print(node)
9591
print("=" * 80)
9692

9793

98-
lista = ListaDuplamenteEncadeada()
94+
list = DoublyLinkedList()
9995

100-
lista.acrescentar(2)
101-
lista.mostrar()
102-
lista.acrescentar(5)
103-
lista.mostrar()
104-
lista.acrescentar(12)
105-
lista.mostrar()
106-
lista.acrescentar(20)
107-
lista.mostrar()
96+
list.append(2)
97+
list.display()
98+
list.append(5)
99+
list.display()
100+
list.append(12)
101+
list.display()
102+
list.append(20)
103+
list.display()
108104

109-
lista.remover(12)
110-
lista.mostrar()
111-
lista.remover(5)
112-
lista.mostrar()
105+
list.delete(12)
106+
list.display()
107+
list.delete(5)
108+
list.display()

0 commit comments

Comments
 (0)