Q2

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.8 kB
3
Indexable
Never
def is_integer(string):
    """ Returns true if the string consists of digits only, false otherwise"""
    return all(i.isdigit() for i in string)


def solution(S):
    """ Creates a new Stack object and applies word machine instructions to it
    Returns error code -1, if:
        integer overflow after addition/substraction
        not enough elements to pop
        not enough elements to duplicate, add, substract
        the stack is empty at the end
    Otherwise, returns the head of Stack after all operations
    """
    new_stack = []
    for command in S.split():
        if is_integer(command):
            new_stack.append(int(command))

        elif command == "DUP":
            if len(new_stack) > 0:
                x = new_stack[-1]
                new_stack.append(x)
            else:
                return -1

        elif command == "POP":
            if len(new_stack) > 0:
                x = new_stack.pop()
            else:
                return -1

        elif command == "+":
            if len(new_stack) < 2:
                return -1
            else:
                x = new_stack.pop()
                y = new_stack.pop()
                res = x + y
                if is_number_valid(res):
                    new_stack.append(res)
                else:
                    return -1

        elif command == "-":
            if len(new_stack) < 2:
                return -1
            else:
                x = new_stack.pop()
                y = new_stack.pop()
                res = x - y
                if is_number_valid(res):
                    new_stack.append(res)
                else:
                    return -1

    if len(new_stack) == 0:
        return -1
    else:
        return new_stack[-1]