Resolução Módulo 5¶

Exercício 1¶

In [1]:
class Stack:

    def __init__(self): # inicia uma pilha vazia
        self.__elements = []

    def push(self,e): # coloca no topo
        self.__elements.append(e)

    def is_empty(self):
        return len(self.__elements) == 0

    def pop(self): # remove do topo
        if not self.is_empty():
            self.__elements.pop()

    def top(self): # consultar o elemento no topo da pilha
        if self.is_empty():
            raise ValueError('Empty Stack!')
        return self.__elements[-1]

    def clear(self):
        self.__elements = []

    def __len__(self):
        return len(self.__elements)

# Ordens de complexidade O(1)
# push e pop piores casos O(N

Exercício 2¶

In [2]:
class StackA:

    def __init__(self, capacidade =100, dtype=str):
        self.__data = np.empty(capacidade, dtype)
        self.__capacidade = capacidade
        self.__it = -1

    def capacidade(self):
        return self.__capacidade

    def is_empty(self):
        return self.__it == -1

    def push(self, e):
        if self.__it != self.__capacidade-1:
            self.__it += 1
            self.__data[self.__it] = e
        else:
            self.add_space()
            self.push(e)

    def add_space(self, n = 50):
        new_data = np.empty(self.__capacidade+n)
        new_data[:self.__capacidade] = self.__data[:self.__capacidade]
        self.__capacidade = self.__capacidade + n
        self.__data = new_data

    def pop(self):
        assert(not self.is_empty())
        self.__it -= 1
        self.__data[self.__it+1] = None

    def top(self):
        assert(not self.is_empty())
        return self.__data[self.__it]

    def clear(self):
        for i in range(0,self.__it):
            self.__data[self.__it] = None
        self.__it = -1

    def __len__(self):
        return self.__it+1

    def __str__(self):
        stack_str = ""
        for i in range(self.__it+1):
            stack_str = str(self.__data[i]) + "\n" + stack_str
        return f"Stack:\n-------\n{stack_str}-----"

Exercício 3¶

In [3]:
def inverter_ex1(s):
    a = Stack()
    for i in s:
        a.push(i)
    if isinstance(s, str):
        aux = ''
        while not a.is_empty():  # percorre se a pilha ate ela estar vazia
            aux = aux + a.top()  # adiciona se sempre o ultimo elemento da pilha à string
            a.pop()  # remove se o ultimo elemento da pilha
        return aux
    s1 = []
    while not a.is_empty():
        s1.append(a.top())
        a.pop()
    return s1

Exercício 4¶

In [ ]:
class Fila:

    def __init__(self, capacidade =10):
        self.__capacidade = capacidade
        self.__fila = []

    def enqueue(self, e):
        if self.__capacidade == len(self.__fila):
            self.add_space()
            self.enqueue(e)
        return self.__fila.append(e)

    def add_space(self, n=10):
        self.__capacidade +=n
        print('Capacidade da pilha aumentada!')

    def first(self):
        assert(not self.is_empty())
        return self.__fila[0]

    def is_empty(self):
        return len(self.__fila)==0

    def dequeue(self):
        return self.__fila.remove(self.__fila[0])
    # self.__fila.pop(0)

    def __str__(self):
        return f"{self.__fila}"

    def clear(self):
        self.__fila = []

    def __len__(self):
        return len(self.__fila)

Exercício 5¶

In [5]:
class FilaNumeros:

    def __init__(self, capacidade=10):
        self.__capacidade = capacidade
        self.__fila = np.zeros(capacidade)
        self.__it = -1

    def enqueue(self, e):
        if self.__it == len(self.__fila)-1:
            self.add_space()
            self.enqueue(e)
        else:
            self.__it += 1
            self.__fila[self.__it] = e

    def add_space(self, n=10):
        novo = np.empty(self.__capacidade+n)
        novo[:self.__capacidade] = self.__fila[:self.__capacidade]
        self.__capacidade += n
        self.__fila = novo
        print('Capacidade da pilha aumentada!')

    def __str__(self):
        return f"{self.__fila}"

    def first(self):
        assert(not self.is_empty())
        return self.__fila[0]

    def is_empty(self):
        return self.__it == -1

    def dequeue(self):
        ans = self.__fila[0]
        for i in range(1, len(self.__fila)):
            self.__fila[i-1] = self.__fila[i]
        self.__it -= 1
        return ans

    def clear(self):
        self.__it = -1
        self.__fila = np.zeros(self.__capacidade)
        return self.__fila

    def __len__(self):
        return self.__it+1

Exercício 7¶

In [6]:
def verif_capicua_deque(s):
    assert(isinstance(s, str))
    from collections import deque
    a = deque(s)
    initial = False
    for i in range(0, len(a)):
        if a[i] == a[len(a)-i-1]:
            initial = True
        else:
            initial = False
            return initial
    return initial

Exercício 6¶

In [7]:
class URL:

    def __init__(self):
        self.__historico = []
        self.__it = -1
        self.frente = 0 # controla o numero de vezes que podemos andar para a frente ou para tras
        self.nruls = 0
        self.tras = 0

    def new_url(self, e):
        self.__historico.append(e)
        self.__it += 1
        self.nruls += 1
        if self.nruls > 1:
            self.tras += 1

    def backward(self):
        assert (len(self.__historico) > 1)
        assert (self.tras <= self.nruls-1)
        self.frente += 1
        self.tras -= 1
        self.__historico.append(self.__historico[self.tras])
        self.__it += 1

    def forward(self):
        assert (self.frente <= self.nruls-1)
        assert (len(self.__historico) > 1)
        self.frente -= 1
        self.tras += 1
        self.__historico.append(self.__historico[self.frente])
        self.__it += 1

    def exit(self):
        self.__historico = []

    def __str__(self):
        return f"{self.__historico}"


def menu():
    a = URL()
    print('Current URL: __blank__')
    print('(n)ew URL| (b)ackward | (f)orward | (e)xit?')
    input1 = input()
    novo_url = ''
    while input1 != '(e)':
        if input1 == '(n)':
            a.new_url(novo_url)
        elif input1 == '(b)':
            a.backward()
        elif input1 == '(f)':
            a.forward()
        print(f'Current URL:{novo_url}')
        print('(n)ew URL| (b)ackward | (f)orward | (e)xit?')
    a.exit()
In [ ]: