minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 2. Reverse Polish notation #17

Open minimanimoh opened 3 years ago

minimanimoh commented 3 years ago
class LinkedListNode:

    def __init__(self, data):
        self.data = data
        self.next = None

class Stack:

    def __init__(self):
        self.num_elements = 0
        self.head = None

    def push(self, data):
        new_node = LinkedListNode(data)
        if self.head is None:
            self.head = new_node
        else:
            new_node.next = self.head
            self.head = new_node
        self.num_elements += 1

    def pop(self):
        if self.is_empty():
            return None
        temp = self.head.data
        self.head = self.head.next
        self.num_elements -= 1
        return temp

    def top(self):
        if self.head is None:
            return None
        return self.head.data

    def size(self):
        return self.num_elements

    def is_empty(self):
        return self.num_elements == 0
minimanimoh commented 3 years ago
def evaluate_post_fix(input_list):
    """
    Evaluate the postfix expression to find the answer

    Args:
       input_list(list): List containing the postfix expression
    Returns:
       int: Postfix expression solution
    """
    # TODO: Iterate over elements 
    # TODO: Use stacks to control the element positions

    def evaluate_post_fix(input_list):
    stack = Stack()
    for element in input_list:
        if element == '*':
            second = stack.pop()
            first = stack.pop()
            output = first * second 
            stack.push(output)
        elif element == '/':
            second = stack.pop()
            first = stack.pop()
            output = int(first / second)
            stack.push(output)
        elif element == '+':
            second = stack.pop()
            first = stack.pop()
            output = first + second
            stack.push(output)
        elif element == '-':
            second = stack.pop()
            first = stack.pop()
            output = first - second
            stack.push(output)
        else:
            stack.push(int(element))
    return stack.pop()
minimanimoh commented 3 years ago

내 질문:

예를 들어 test_case_1 = [[“3”, “1", “+”, “4", “”], 16] 가 있다면, 이 리스트의 elements을 알아서 (3 + 1) 4 로 배치하여 16으로 나오도록 코드를 짜는 것으로 이해를 했습니다. 그런데, Second = stack.pop() First = stack.pop() 이 부분이 어떻게 실제로 작용되지 잘 모르겠습니다. Pop 함수는 구체적으로 괄호 안의 위치를 지정해주지 않으면 마지막 항목을 꺼내서 사용하고 삭제하고 돌려준다고 알고 있는데. 실제 아래 test_case_1로 적용해보자면 어떻게 꺼내지는 것인가요?