Last active
May 23, 2024 11:11
-
-
Save RickBarretto/749eac74df7c5163fe45ae57bd99455e to your computer and use it in GitHub Desktop.
A simple Stack Machine VM created for the Python's Workshop that I I'll teach.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright 2024 RickBarretto | |
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
""" | |
from operations2 import ops | |
# mostrar uso do assing | |
# mostrar no quadro como funciona uma lista, e quais seus principais métodos | |
stack = [] | |
# demosntrar exemplos de variáveis booleanas | |
running = True | |
while running: | |
print("Stack ops: [push / pop / show]") | |
print("Math ops: [add / sub / mul / div]") | |
# explicar string | |
# explicar input | |
# explicar strip | |
# explicar split | |
op, *values = input(">> ").strip().split(" ") | |
values = [int(value) for value in values] | |
# fazer usando if-else primeiro, sem uso de dicionários | |
# * chama-se cada função dentro do if-else (fazer push, pop e add) | |
# fazer usando for-loop primeiro | |
# * fazer sub e end | |
# colocar funções em outro módulo | |
# explicar importing | |
# refatorar para list-comprehension | |
# refatorar módulo operations para usar classes | |
# usar try-except aqui para finalizar | |
try: | |
operation_function = ops[op] | |
operation_function(stack, values) | |
print() | |
except KeyError: | |
print("Comando digitado não existe.") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright 2024 RickBarretto | |
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
""" | |
# ao final, remover duplicação de código usando essas funções | |
def _show_needed_stack_size(needed_size: int): | |
print(f"Sua stack é insuficiente. São necessários {needed_size} valores para a operação.") | |
print("Dica: use o comando 'push' para inserir elementos na stack.") | |
def _show_command_does_not_get_args(command: str): | |
print(f"O comando '{command}' não recebe argumentos.") | |
# primeiro escreva as funções como: | |
# | |
# def pop(stack, *values): | |
# if values: | |
# print("Sua stack é insuficiente. São necessários 2 valores para a operação.") | |
# print("Dica: use o comando 'push' para inserir elementos na stack.") | |
# return | |
# | |
# if not stack: | |
# print("O comando 'pop' não recebe argumentos.") | |
# return | |
# | |
# print(stack.pop()) | |
# | |
# usando o dicionário: | |
# | |
# ops = { | |
# "end": end, | |
# "show": show, | |
# "push": push, | |
# "pop": pop, | |
# "add": add, | |
# "sub": sub, | |
# "mul": mul, | |
# "div": div, | |
# } | |
# depois escreva as funções como: | |
# | |
# def pop(stack, *values): | |
# if values: | |
# _show_command_does_not_get_args("pop") | |
# return | |
# | |
# if not stack: | |
# _show_needed_stack_size(1) | |
# return | |
# | |
# print(stack.pop()) | |
def end(stack, values): | |
if values: | |
_show_command_does_not_get_args("end") | |
return | |
exit() | |
def show(stack, values): | |
if values: | |
_show_command_does_not_get_args("show") | |
return | |
print(stack) | |
def push(stack, values): | |
for value in values: | |
stack.append(value) | |
def pop(stack, values): | |
if values: | |
_show_command_does_not_get_args("pop") | |
return | |
if not stack: | |
_show_needed_stack_size(1) | |
return | |
print(stack.pop()) | |
def add(stack, values): | |
if values: | |
_show_command_does_not_get_args("add") | |
return | |
if len(stack) < 2: | |
_show_needed_stack_size(2) | |
return | |
a, b = stack.pop(), stack.pop() | |
push(stack, a + b) | |
def sub(stack, values): | |
if values: | |
_show_command_does_not_get_args("sub") | |
return | |
if len(stack) < 2: | |
_show_needed_stack_size(2) | |
return | |
b, a = stack.pop(), stack.pop() | |
push(stack, a - b) | |
def mul(stack, values): | |
if values: | |
_show_command_does_not_get_args("mul") | |
return | |
if len(stack) < 2: | |
_show_needed_stack_size(2) | |
return | |
b, a = stack.pop(), stack.pop() | |
push(stack, a * b) | |
def div(stack, values): | |
if values: | |
_show_command_does_not_get_args("div") | |
return | |
if len(stack) < 2: | |
_show_needed_stack_size(2) | |
return | |
b, a = stack.pop(), stack.pop() | |
if b == 0: | |
print("Divisão por 0 não permitida.") | |
push(stack, a, b) | |
return | |
push(stack, a / b) | |
ops = { | |
"end": end, | |
"show": show, | |
"push": push, | |
"pop": pop, | |
"add": add, | |
"sub": sub, | |
"mul": mul, | |
"div": div, | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright 2024 RickBarretto | |
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
""" | |
# ao final, remover duplicação de código | |
# usando classes | |
from typing import Any | |
# Mostrar criação da classe base | |
class Command: | |
def __init__(self, command: str, arity: int, has_args: bool) -> None: | |
self.command: str = command | |
self.arity: int = arity | |
self.has_args: int = has_args | |
def match_requisites(self, stack, args): | |
if args and not self.has_args: | |
self.show_cant_get_params() | |
return False | |
if len(stack) < self.arity: | |
self.show_insufficient_stack() | |
return False | |
return True | |
def show_insufficient_stack(self): | |
print("Sua stack é insuficiente.", | |
f"São necessários {self.arity} valores para a operação '{self.command}'.") | |
print("Dica: use o comando 'push' para inserir elementos na stack.") | |
def show_cant_get_params(self): | |
print(f"O comando '{self.command}' não recebe argumentos.") | |
def __call__(self, stack: list[int], args: list[int]) -> Any: | |
if self.match_requisites(stack, args): | |
self.operate(stack, args) | |
# Mostrar criação das classes filhas | |
class End(Command): | |
# Desafio final: criar função help e menu help. | |
def help(self) -> str: | |
return "Finaliza o programa..." | |
def operate(self, stack: list[int], args): | |
exit() | |
class Show(Command): | |
def operate(self, stack: list[int], args): | |
print(stack) | |
class Push(Command): | |
def operate(self, stack: list[int], args): | |
stack.extend(args) | |
class Pop(Command): | |
def operate(self, stack: list[int], args): | |
print(stack.pop()) | |
class Add(Command): | |
def operate(self, stack: list[int], args): | |
a, b = stack.pop(), stack.pop() | |
stack.append(a + b) | |
class Sub(Command): | |
def operate(self, stack: list[int], args): | |
a, b = stack.pop(), stack.pop() | |
stack.append(a - b) | |
class Mul(Command): | |
def operate(self, stack: list[int], args): | |
a, b = stack.pop(), stack.pop() | |
stack.append(a * b) | |
class Div(Command): | |
def operate(self, stack: list[int], args): | |
b, a = stack.pop(), stack.pop() | |
try: | |
stack.append(a / b) | |
except ZeroDivisionError: | |
print("Divisão por 0 não permitida.") | |
stack.extend([a, b]) | |
# Mostrar criação das instâncias | |
# usando o seguinte dicionário | |
# ops = { | |
# "end": End("end", 0, False), | |
# "show": Show("show", 0, False), | |
# "push": Push("push", 0, True), | |
# "pop": Pop("pop", 1, False), | |
# "add": Add("add", 2, False), | |
# "sub": Sub("sub", 2, False), | |
# "mul": Mul("mul", 2, False), | |
# "div": Div("div", 2, False), | |
# } | |
# então | |
operations = [ | |
End("end", 0, False), | |
Show("show", 0, False), | |
Push("push", 0, True), | |
Pop("pop", 1, False), | |
Add("add", 2, False), | |
Sub("sub", 2, False), | |
Mul("mul", 2, False), | |
Div("div", 2, False), | |
] | |
ops = {operation.command: operation for operation in operations} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment