diff --git a/algorithms_project/algorithms/arrays/first_uni_char.py b/algorithms_project/algorithms/arrays/first_uni_char.py index ae0ddab..08b9f05 100644 --- a/algorithms_project/algorithms/arrays/first_uni_char.py +++ b/algorithms_project/algorithms/arrays/first_uni_char.py @@ -5,17 +5,17 @@ def firstUniqChar(self, s: str) -> int: if not d.get(ch): d[ch] = [idx, 1] else: - d[ch][1] +=1 - + d[ch][1] += 1 + for ch, val in d.items(): if val[1] == 1: return val[0] return -1 - + + solution = Solution() print(solution.firstUniqChar("leetcode")) - solution = Solution() -print(solution.firstUniqChar("loveleetcode")) \ No newline at end of file +print(solution.firstUniqChar("loveleetcode")) diff --git a/algorithms_project/algorithms/arrays/two_pointer.py b/algorithms_project/algorithms/arrays/two_pointer.py index edc467c..39c55c0 100644 --- a/algorithms_project/algorithms/arrays/two_pointer.py +++ b/algorithms_project/algorithms/arrays/two_pointer.py @@ -1,20 +1,21 @@ class Solution: def reverseWords_manual(s): res = '' - l, r = 0, 0 + left, r = 0, 0 while r < len(s): if s[r] != ' ': r += 1 else: - res += s[l:r+1][::-1] + res += s[left:r+1][::-1] r += 1 - l = r - + left = r + res += ' ' - res += s[l:r + 2][::-1] + res += s[left:r + 2][::-1] return res[1:] - + + cat = Solution.reverseWords_manual("rac tar") print(cat) @@ -23,6 +24,7 @@ class Solution2: def reverserWords(s): return ' '.join(word[::-1] for word in s.split()) + reverseword = Solution2.reverserWords("I evol edocteel") print(reverseword) @@ -30,14 +32,13 @@ def reverserWords(s): class Solution3: def reverseWords_manual1(s): res = '' - l = 0 for r in range(len(s) + 1): if r == len(s) or s[r] == ' ': - res += s[l:r][::-1] + res += s[:r][::-1] if r < len(s): res += ' ' - l = r + 1 return res + reverseword3 = Solution3.reverseWords_manual1("Let's take LeetCode contest") -print(reverseword3) \ No newline at end of file +print(reverseword3) diff --git a/algorithms_project/algorithms/arrays/two_sum.py b/algorithms_project/algorithms/arrays/two_sum.py index acd7912..972dad0 100644 --- a/algorithms_project/algorithms/arrays/two_sum.py +++ b/algorithms_project/algorithms/arrays/two_sum.py @@ -1,11 +1,12 @@ from typing import List + class Problem1: def two_sum(self, A: List[int], k: int) -> List[int]: n = len(A) result = [-1, -1] min_j = n # para controlar o menor j encontrado - + # Percorrer todos os pares i List[int]: result = [i, j] min_j = j break # para i, não precisa buscar mais i menores, pois queremos i máximo para esse j - return result \ No newline at end of file + return result diff --git a/algorithms_project/algorithms/arrays/two_sum2.py b/algorithms_project/algorithms/arrays/two_sum2.py index fec499a..9d10e91 100644 --- a/algorithms_project/algorithms/arrays/two_sum2.py +++ b/algorithms_project/algorithms/arrays/two_sum2.py @@ -18,7 +18,7 @@ -O complemento atual é o valor que falta para atingir o target. Para cada número num em nums, calculamos: complemento = target - num - + verifica no dicionario se este valor ja foi visto antes. num + complemento = target """ @@ -41,12 +41,9 @@ def twoSum(self, nums, target): return [-1, -1] + solutions = Solution() -a = [2,7,11,15] +a = [2, 7, 11, 15] target = 17 print(solutions.twoSum(a, target)) - - - - diff --git a/algorithms_project/algorithms/linked_lists/Aula01.py b/algorithms_project/algorithms/linked_lists/Aula01.py index 530a127..af8ee6d 100644 --- a/algorithms_project/algorithms/linked_lists/Aula01.py +++ b/algorithms_project/algorithms/linked_lists/Aula01.py @@ -3,32 +3,33 @@ def __init__(self, value): self.value = value # valor guardado no nó self.next = None # referência para o próximo nó self.prev = None # referência para o nó anterior - + + class DoublyLinkedList: def __init__(self): self.head = None # inicio da lista ou a "cabeça" - self.tail = None # fim da lista ou "rabo" - - def add_to_front(self, value): # ********* 👉 Coloca alguém na frente da fila. ****************** + self.tail = None # fim da lista ou "rabo" + + def add_to_front(self, value): # ********* 👉 Coloca alguém na frente da fila. ****************** new_node = Node(value) # Cria um novo nó if not self.head: # Se a lista estiver vazia self.head = self.tail = new_node else: new_node.next = self.head # Novo nó aponta para o antigo começo self.head.prev = new_node # antigo começo aponta para o novo nó - self.head = new_node # atualiza o começo - - def add_to_end(self, value): # ********* 👉 Coloca alguém no fim da fila. ****************** + self.head = new_node # atualiza o começo + + def add_to_end(self, value): # ********* 👉 Coloca alguém no fim da fila. ****************** new_node = Node(value) if not self.tail: # se a lista estiver vazia self.head = self.tail = new_node else: - new_node.prev = self.tail # novo nó aponta para o antigo fim + new_node.prev = self.tail # novo nó aponta para o antigo fim self.tail.next = new_node # antigo fim aponta para o novo nó - self.tail = new_node # atualiza o fim - + self.tail = new_node # atualiza o fim + def remove_from_front(self): # ********* 👉 Remove o primeiro da fila. ****************** - if not self.head: + if not self.head: return None # confere se a lista não está vazia removed_value = self.head.value # guarda o valor removido if self.head == self.tail: # só tinha 1 nó @@ -37,9 +38,9 @@ def remove_from_front(self): # ********* 👉 Remove o primeiro da fila. ****** self.head = self.head.next # move o head pro próximo self.head.prev = None # o novo começo não tem anterior return removed_value - - def remove_from_end(self): # ********* 👉 Remove o ultimo da fila. ****************** - if not self.tail: + + def remove_from_end(self): # ********* 👉 Remove o ultimo da fila. ****************** + if not self.tail: return None # confere se a lista não está vazia removed_value = self.tail.value # guarda o valor removido if self.head == self.tail: # só tinha 1 nó @@ -47,16 +48,17 @@ def remove_from_end(self): # ********* 👉 Remove o ultimo da fila. ****** else: self.tail = self.tail.prev # move o tail pro anterior self.tail.next = None # o novo fim não tem próximo - return removed_value + return removed_value - def to_list(self): # ********* Só percorre e devolve os valores como lista Python [1,2,3,...]. ****************** - current = self.head + def to_list(self): # ********* Só percorre e devolve os valores como lista Python [1,2,3,...]. ****************** + current = self.head items = [] while current: items.append(current.value) # percorre do começo até o fim current = current.next return items - + + dll = DoublyLinkedList() @@ -75,6 +77,3 @@ def to_list(self): # ********* Só percorre e devolve os valores co print(dll.remove_fron_end()) # 👉 remove 5 print(dll.to_list()) # 👉 [2, 3, 4] - - - diff --git a/algorithms_project/algorithms/linked_lists/ListNode.py b/algorithms_project/algorithms/linked_lists/ListNode.py index d91914a..14b9ef0 100644 --- a/algorithms_project/algorithms/linked_lists/ListNode.py +++ b/algorithms_project/algorithms/linked_lists/ListNode.py @@ -1,20 +1,22 @@ class ListNode: def __init__(self, val=0, next=None): # Cada "nó" da lista tem um valor (val) - self.val = val + self.val = val # E uma referência para o próximo nó (next) self.next = next + def create_linked_list(lst): head = None - # Percorremos a lista original de trás para frente + # Percorremos a lista original de trás para frente for val in reversed(lst): # Cada novo valor vira a cabeça da lista head = ListNode(val, head) return head + def print_linked_list(head): values = [] while head: @@ -23,5 +25,3 @@ def print_linked_list(head): # Andamos para a o próximo nó head = head.next print(values) - - \ No newline at end of file diff --git a/algorithms_project/algorithms/linked_lists/ReverseList.py b/algorithms_project/algorithms/linked_lists/ReverseList.py index 7ddc8f8..244b63f 100644 --- a/algorithms_project/algorithms/linked_lists/ReverseList.py +++ b/algorithms_project/algorithms/linked_lists/ReverseList.py @@ -1,35 +1,39 @@ from typing import Optional from ListNode import ListNode, create_linked_list, print_linked_list + class Solution: def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: # abaixo será criado uma nova lista vazia (vai ser a lista invertida) - new_list = None + new_list = None # Enquanto ainda existir algum nó (Elemento) na lista original while head: # Guardamos o próximo nó para não perder o resta da lista - + next_node = head.next - + # Fazemos o nó atual apontar para a nova lista (invertendo a direção) head.next = new_list - # Agora o nó atual passa a ser a cabeça da nova lista + # Agora o nó atual passa a ser a cabeça da nova lista new_list = head - # e seguimos para o próximo nó da lista original + # e seguimos para o próximo nó da lista original head = next_node return new_list - + + # criamos um "objeto" da classe Solution, que tem o método de inverter a lista reverse_list = Solution() -# criamos uma lista com os números -head = create_linked_list([1,2,3,4,5]) + +# criamos uma lista com os números +head = create_linked_list([1, 2, 3, 4, 5]) + # chamamos a função que inverte a lista: vira 5 → 4 → 3 → 2 → 1 reversed_head = reverse_list.reverseList(head) + print_linked_list(reversed_head) - \ No newline at end of file diff --git a/algorithms_project/algorithms/linked_lists/midddleNode.py b/algorithms_project/algorithms/linked_lists/midddleNode.py index a81bc14..b6181d4 100644 --- a/algorithms_project/algorithms/linked_lists/midddleNode.py +++ b/algorithms_project/algorithms/linked_lists/midddleNode.py @@ -6,6 +6,8 @@ # def __init__(self, val=0, next=None): # self.val = val # self.next = next + + class Solution(): def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: """ @@ -26,13 +28,14 @@ def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: head = head.next return head + # Criamos um objeto da classe Solution middle_node = Solution() # Criamos uma lista -head = create_linked_list([1,2,3,4,5]) +head = create_linked_list([1, 2, 3, 4, 5]) # Chamamos a função para encontrar o meio middle_node = middle_node.middleNode(head) -print_linked_list(middle_node) \ No newline at end of file +print_linked_list(middle_node) diff --git a/algorithms_project/algorithms/queues/sandbox.py b/algorithms_project/algorithms/queues/sandbox.py index f09312d..1b58831 100644 --- a/algorithms_project/algorithms/queues/sandbox.py +++ b/algorithms_project/algorithms/queues/sandbox.py @@ -55,4 +55,3 @@ print(fila.popleft()) print(fila) - diff --git a/algorithms_project/algorithms/queues/worker.py b/algorithms_project/algorithms/queues/worker.py index dbf4574..935c763 100644 --- a/algorithms_project/algorithms/queues/worker.py +++ b/algorithms_project/algorithms/queues/worker.py @@ -7,9 +7,10 @@ def worker(queue): while not queue.empty(): task = queue.get() print(f"{threading.current_thread().name} processing: {task}") - time.sleep(1) #process simulation + time.sleep(1) # process simulation queue.task_done() + # Queue tasks tasks = queue.Queue() @@ -25,5 +26,5 @@ def worker(queue): t.start() -tasks.join() # Wait for all tasks to be processed +tasks.join() # Wait for all tasks to be processed print("All the tasks are done") diff --git a/algorithms_project/algorithms/sliding_window/contains_duplicate.py b/algorithms_project/algorithms/sliding_window/contains_duplicate.py index f7c5c55..7a43d11 100644 --- a/algorithms_project/algorithms/sliding_window/contains_duplicate.py +++ b/algorithms_project/algorithms/sliding_window/contains_duplicate.py @@ -6,7 +6,7 @@ def containnumsNearbyDuplicate(self, nums, k): :rtype: bool """ - i = 0 + i = 0 while i < len(nums): j = i + 1 @@ -18,5 +18,6 @@ def containnumsNearbyDuplicate(self, nums, k): i += 1 return False + numsolution = Numsolution() -print(numsolution.containnumsNearbyDuplicate([1,2,3,1], 3)) \ No newline at end of file +print(numsolution.containnumsNearbyDuplicate([1, 2, 3, 1], 3)) diff --git a/algorithms_project/algorithms/sliding_window/solution.py b/algorithms_project/algorithms/sliding_window/solution.py index cfb8012..6c3d001 100644 --- a/algorithms_project/algorithms/sliding_window/solution.py +++ b/algorithms_project/algorithms/sliding_window/solution.py @@ -1,29 +1,27 @@ class Solution: def maximumLengthSubstring(self, s: str) -> int: - l, r = 0, 0 + left, right = 0, 0 _max = 1 counter = {} counter[s[0]] = 1 - while r < len(s) -1: - r+=1 - if counter.get(s[r]): - counter[s[r]] += 1 + while right < len(s) - 1: + right += 1 + if counter.get(s[right]): + counter[s[right]] += 1 else: - counter[s[r]] = 1 + counter[s[right]] = 1 - while counter[s[r]] == 3: - counter[s[l]] -= 1 - l += 1 - _max = max(_max, r-l+1) - + while counter[s[right]] == 3: + counter[s[left]] -= 1 + left += 1 + _max = max(_max, right - left + 1) return _max - solution = Solution s = "bcbbbcbaaaaaaabcbdaaddddacbbbbb" -result = solution.maximumLengthSubstring(3,s) +result = solution.maximumLengthSubstring(3, s) -print(f'Maximum length of substring with 3 a\'s is {result}') # Output: 2 \ No newline at end of file +print(f'Maximum length of substring with 3 a\'s is {result}') # Output: 2 diff --git a/algorithms_project/algorithms/tries/trie.py b/algorithms_project/algorithms/tries/trie.py index fd5215e..1020e69 100644 --- a/algorithms_project/algorithms/tries/trie.py +++ b/algorithms_project/algorithms/tries/trie.py @@ -3,10 +3,11 @@ def __init__(self): self.children = {} self.is_end_of_word = False + class Trie: def __init__(self): self.root = TrieNode() - + def insert(self, word): current_node = self.root print(f"Inserindo a palavra: {word}") @@ -39,14 +40,12 @@ def starts_with(self, prefix): return True - - trie = Trie() trie.insert("apple") -#trie.insert("banana") -#trie.insert("app") -#trie.insert("orange") +# trie.insert("banana") +# trie.insert("app") +# trie.insert("orange") -#print(trie.search("apple")) \ No newline at end of file +# print(trie.search("apple")) diff --git a/algorithms_project/tests/test_arrays/test_two_sum.py b/algorithms_project/tests/test_arrays/test_two_sum.py index f8cfebe..9f38117 100644 --- a/algorithms_project/tests/test_arrays/test_two_sum.py +++ b/algorithms_project/tests/test_arrays/test_two_sum.py @@ -1,16 +1,20 @@ from algorithms.arrays.two_sum import Problem1 + def test_two_sum_basic(): - assert sorted(Problem1().two_sum([2, 7, 11, 15], 9)) == [0, 1] # Vai retornar os indices 0 e 1 devido a soma de 2 e 7 + assert sorted(Problem1().two_sum([2, 7, 11, 15], 9)) == [0, 1] # Vai retornar os indices 0 e 1 devido a soma de 2 e 7 + def test_example1(): - assert Problem1().two_sum([1, 2, 3, 4], 5) == [1, 2] # Vai retornar os indices 1 e 2 devido a soma de 2 e 3 + assert Problem1().two_sum([1, 2, 3, 4], 5) == [1, 2] # Vai retornar os indices 1 e 2 devido a soma de 2 e 3 + def test_example2(): - assert Problem1().two_sum([-1, 2, 3, 4], 10) == [-1, -1] # Vai retornar os indices -1 e -1 devido a soma de todos os indices não chegar a 10 + assert Problem1().two_sum([-1, 2, 3, 4], 10) == [-1, -1] # Vai retornar os indices -1 e -1 devido a soma de todos os indices não chegar a 10 + def test_example3(): - assert Problem1().two_sum([-1, -1, 2, -1], 1) == [1, 2] # Vai retornar os indices 1 e 2 devido a soma de -1 + 2 chegar a 1 + assert Problem1().two_sum([-1, -1, 2, -1], 1) == [1, 2] # Vai retornar os indices 1 e 2 devido a soma de -1 + 2 chegar a 1 def test_no_pair():