def checkSatisfiability(self, postFixList):
        propStack = Stack()
        p = re.compile('[a-zA-Z0-1]')
        for op in postFixList:
            if op == 'ID' or p.match(op):
                propStack.push(Symbol(op))
            elif op in ['NOT', '!']:
                propStack.push(Not(propStack.pop()))
            elif op in ['AND', '/\\', ',', 'COMMA']:
                p2 = propStack.pop()
                p1 = propStack.pop()
                propStack.push(And(p1, p2))
            elif op in ['OR', '\\/']:
                p2 = propStack.pop()
                p1 = propStack.pop()
                propStack.push(Or(p1, p2))
            elif op in ['IFF', '<=>']:
                p2 = propStack.pop()
                p1 = propStack.pop()
                propStack.push(Iff(p1, p2))
            elif op in ['IMPLIES', '=>']:
                p2 = propStack.pop()
                p1 = propStack.pop()
                propStack.push(Implies(p1, p2))

        print("propStack size: ", propStack.size())

        if propStack.size() == 1:
            p3 = propStack.pop()
            # print ("Expression for satisfiability:", p3)
            print("Is sat or not : ", is_sat(p3))
        else:
            print("Error while checking Is sat or not")
Ejemplo n.º 2
0
def dfs_tk(start, end, w):
    fringe = Stack()
    fringe.push((0, start, nodes[start][0], 0, []))
    visited = set()
    all_lines = set()

    end_y = nodes[end][0][0]
    end_x = nodes[end][0][1]

    while fringe.size() is not 0:
        s = fringe.pop()

        if len(s) > 5:
            sy = (-abs((float(s[2][1])) + maxy) + height) * scaleh - 2
            sx = abs((float(s[2][0])) + maxx) * scalew + 8
            ey = (-abs(float(s[5][1]) + maxy) + height) * scaleh - 2
            ex = abs((float(s[5][0])) + maxx) * scalew + 8

            w.itemconfig(lines_dict[(sy, sx, ey, ex)], fill="blue", width=2)
            w.itemconfig(lines_dict[(ey, ex, sy, sx)], fill="blue", width=2)

        if goal_test(s[1], end):  # if the state is won
            return s[3], s[4], all_lines  # return the moves

        if s[1] in visited:
            continue

        visited.add(s[1])

        children = get_children(s[1])
        for child in children:
            if child[1] not in visited:
                red_lines = list(s[4])
                sy = (-abs((float(s[2][1])) + maxy) + height) * scaleh - 2
                sx = abs((float(s[2][0])) + maxx) * scalew + 8
                ey = (-abs(float(child[2][1]) + maxy) + height) * scaleh - 2
                ex = abs((float(child[2][0])) + maxx) * scalew + 8
                red_lines.append((sy, sx, ey, ex))
                all_lines.add((sy, sx, ey, ex))
                # w.create_line((sy, sx, ey, ex), fill="mediumblue", width = 2)
                w.itemconfig(lines_dict[(sy, sx, ey, ex)], fill="red", width=2)
                w.itemconfig(lines_dict[(ey, ex, sy, sx)], fill="red", width=2)
                fringe.push((child[0], child[1], child[2], s[3] + child[0],
                             red_lines, s[2]))
        redraw(w)
        # if random.randint(0, 1000) > 999:
        #     w.update()
        #         # print(abs(float(s[3][1]))-70, abs(float(s[3][0]))-30, abs(float(child[2][1]))-70, abs(float(child[2][0]))-30)
        # w.create_line((abs(float(s[3][1]))-70)*20, (abs(float(s[3][0]))-30)*20, (abs(float(child[2][1]))-70)*20, (abs(float(child[2][0]))-30)*20)

    if fringe.size() is 0:
        return -1
Ejemplo n.º 3
0
def test_stack():
    s = Stack()
    print(s.is_empty())
    s.push(4)
    s.push('dog')
    print(s.peek())
    s.push(True)
    print(s.size())
    print(s.is_empty())
    s.push(8.4)
    print(s.pop())
    print(s.pop())
    print(s.size())
Ejemplo n.º 4
0
def convert(expression: str) -> str:
    expression = list(expression)
    output = []
    opstack = Stack()
    precedence = {"(":1,"-":2,"+":2,"/":3,"*":3}
    for token in expression:
        if token in 'ABCD':
            output.append(token)

        elif token == '(':
            opstack.push(token)

        elif token == ")":
            topElement = opstack.pop()
            while topElement != "(":
                output.append(topElement)
                topElement = opstack.pop()          

        elif token in precedence:
            lowerPrec = False
            while opstack.size() > 1 and not lowerPrec:
                if opstack.peek() in precedence and precedence[opstack.peek()] >= precedence[token]:
                    output.append(opstack.pop())
                else:
                    lowerPrec = True
            opstack.push(token)

    while not opstack.isEmpty():
        output.append(opstack.pop())
    return " ".join(output)
Ejemplo n.º 5
0
def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()
    # postfixList = []
    digits = "0123456789"
    operators = "+-*/"

    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        elif token in operators:
            secondOperand = operandStack.pop()
            firstOperand = operandStack.pop()
            # if token == operators[0]:
            #     Operand = firstOperand + secondOperand
            # elif token == operators[1]:
            #     Operand = firstOperand - secondOperand
            # elif token == operators[2]:
            #     Operand = firstOperand * secondOperand
            # elif token == operators[3]:
            #     Operand = firstOperand / secondOperand
            Operand = doMath(token, firstOperand, secondOperand)
            operandStack.push(Operand)

    assert(operandStack.size() == 1)
    res = operandStack.pop()
    return res
Ejemplo n.º 6
0
class NewsQueue:
    # generate a random cycle and week day to simulate, use a Stack to keep emails in last in first out order
    def __init__(self):
        self.cycleday = random.randrange(1, 7)
        self.weekday = random.randrange(0, 5)
        self.items = Stack()

    # generate the emails for the day and add them to the items Stack
    def getMail(self):

        # 1: daily announcement emails -- every day
        weekdaynames = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
        self.items.push("\tDaily Announcements: " +
                        weekdaynames[self.weekday] + ", Day " +
                        str(self.cycleday))

        # 2: detention emails -- 1/5 days a week
        if self.weekday == 4:
            self.items.push("\tServe your detentions, folks")

        # 3: home game emails -- on any given day, 5 sports teams each have a 1/5 chance of having a home game
        for i in range(5):
            t = Team()

            if t.gameday == self.weekday:
                self.items.push("\t" + t.getMessage())

        # 4: club emails -- on cycle days 1, 3, and 5, 10 clubs have a 1/3 chance of meeting
        for i in range(10):
            c = Club()

            if c.meetday == self.cycleday:
                self.items.push("\t" + c.getMessage())

    def size(self):
        return self.items.size()

    # pop all items to show inbox in order
    def dumpItems(self):
        s = "RCDS News: " + str(self.items.size()) + " unread\n"
        for i in range(self.items.size()):
            s += self.items.pop() + "\n"
        return s
def reverse(strng):
    lst = Stack()
    rst = []
    i = 0
    while lst.size() < len(strng):
        lst.push(strng[i])
        i += 1
    while len(rst) < len(strng):
        rst.append(lst.pop())
    return ''.join(rst)
Ejemplo n.º 8
0
def rev_string(mystr):
    s = Stack()
    for char in mystr:
        s.push(char)

    reversed = ""
    while s.size() > 0:
        reversed += s.pop()

    return reversed
Ejemplo n.º 9
0
def revstring(myStr):
    s = Stack()
    for ch in myStr:
        s.push(ch)

    emptyStr = ""

    i = 0
    while i < s.size():
        emptyStr = emptyStr + s.pop()

    return emptyStr
Ejemplo n.º 10
0
def moveTower(height,fromPole, toPole, withPole):
	fromPole = Stack()
	toPole = Stack()
	withPole = Stack()
	for i in range(height):
		fromPole.push(i)
	if fromPole.size() == 1:
		Disk = fromPole.pop()
		toPole.push(Disk)
	else:
		moveTower(height-1, fromPole, toPole, withPole)
		print fromPole, toPole, withPole
Ejemplo n.º 11
0
def get_constituency_graph(input_tmp):
    tmp_result = input_tmp

    if _cut_root_node:
        parse_str = cut_root_node(str(tmp_result['parse']))
    else:
        parse_str = str(tmp_result['parse'])
    for punc in ['(', ')']:
        parse_str = parse_str.replace(punc, ' ' + punc + ' ')
    parse_list = str(parse_str).split()

    res_graph = nx.DiGraph()
    pstack = Stack()
    idx = 0
    while idx < len(parse_list):
        if parse_list[idx] == '(':
            new_node = Node(word=parse_list[idx + 1], id_=idx + 1, type_=1)
            res_graph.add_node(new_node)
            pstack.push(new_node)

            if pstack.size() > 1:
                node_2 = pstack.pop()
                node_1 = pstack.pop()
                res_graph.add_edge(node_1, node_2)
                pstack.push(node_1)
                pstack.push(node_2)
        elif parse_list[idx] == ')':
            pstack.pop()
        elif parse_list[idx] in tmp_result['tok']:
            new_node = Node(word=parse_list[idx], id_=idx, type_=0)
            node_1 = pstack.pop()
            if node_1.id != new_node.id:
                res_graph.add_edge(node_1, new_node)
            pstack.push(node_1)
        idx += 1

    max_id = 0
    for n in res_graph.nodes():
        if n.type == 0 and n.id > max_id:
            max_id = n.id

    min_id = 99999
    for n in res_graph.nodes():
        if n.type == 0 and n.id < min_id:
            min_id = n.id

    for n in res_graph.nodes():
        if n.type == 0 and n.id == max_id:
            n.tail = True
        if n.type == 0 and n.id == min_id:
            n.head = True
    return res_graph
Ejemplo n.º 12
0
def main(argv):
    windowName = ""
    clickCount = 10
    sleepSec = 2
    try:
        opts, args = getopt.getopt(argv, "hw:c:s:",
                                   ["window=", "clickcount=", "sleep="])
    except getopt.GetoptError:
        print 'PyWinMonkey.py -w <Window Name> -c <Click Count=10> -s <Sleep Seconds Before Start=2>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'PyWinMonkey.py -w <Window Name> -c <Click Count=10> -s <Sleep Seconds Before Start>'
            sys.exit()
        elif opt in ("-w", "--window"):
            windowName = arg
        elif opt in ("-c", "--clickcount"):
            clickCount = int(arg)
        elif opt in ("-s", "--sleep"):
            sleepSec = int(arg)
    print(windowName + ", " + str(clickCount) + ", " + str(sleepSec))
    if windowName == "":
        print("Error: Window name not found...")
    time.sleep(sleepSec)
    from pythonds.basic.stack import Stack
    s = Stack()
    win32gui.EnumWindows(callback, s)

    win_x = -1
    win_y = -1
    win_width = -1
    win_height = -1

    while s.size() > 0:
        win = s.pop()
        if win[4] == windowName:
            win_x = win[0]
            win_y = win[1]
            win_width = win[2]
            win_height = win[3]
            # print ("window status: "+str(win))
            break

    if win_x > -1 and win_y > -1:
        for i in xrange(int(clickCount)):
            print(str(i))
            xposition = random.randint(win_x + 10, win_x + win_width - 10)
            yposition = random.randint(win_y + 10, win_y + win_height - 10)
            print(str(xposition) + "," + str(yposition))
            pyautogui.click(xposition, yposition)
Ejemplo n.º 13
0
def divide_by_two(number):
    s = Stack()

    while number > 0 :
        remainder = number % 2
        s.push(remainder)
        number = number // 2

    size = s.size()
    result = ""
    for item in range(size):
        result += str(s.pop())
    
    return result
Ejemplo n.º 14
0
def buildParseTree(fpexp):
    fplist = fpexp.split()  #splitting a string of expression into list
    #(type list)
    pStack = Stack()  #create empty stack
    #(type 'instance')
    eTree = BinaryTree('')  #top root value
    #(type 'instance')
    pStack.push(eTree)  #pushed current root into the stack
    print pStack.size()
    currentTree = eTree  #current position at a time
    #(type 'instance')

    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')  #inserts an empty node as a leftChild
            #print currentTree
            pStack.push(currentTree)  #pushes current tree into the stack
            print 'StackSize: {},  root: {}      iteration(push): {} '.format(
                pStack.size(), currentTree.getRootVal(), i)
            currentTree = currentTree.getLeftChild(
            )  #sets current position to the leftChild

        elif i not in ['+', '-', '*', '/', ')']:
            print '-----before root: {} '.format(currentTree.getRootVal())
            currentTree.setRootVal(
                int(i)
            )  #we are located at the node so set  the root value to the number
            #parent = pStack.pop()  #???
            #print 'StackSize: {},  parent: {}     iteration(pop): digits'.format(pStack.size(), parent.getRootVal())
            #currentTree = parent  #this sets the current position to the parent node
            currentTree = pStack.pop()
            print 'StackSize: {},     iteration(pop): digits'.format(
                pStack.size())
            print '-----after root: {} '.format(currentTree.getRootVal())

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(
                i)  #set the value to the operator for "currentTree"
            currentTree.insertRight('')  # descend to the right child
            pStack.push(
                currentTree
            )  #push the new tree to the stack (will it push last updated node or the whole tree? Will it souble it?)
            print 'StackSize: {}, root: {}      iteration(push): {}'.format(
                pStack.size(), currentTree.getRootVal(), i)
            currentTree = currentTree.getRightChild(
            )  # this set the current position to the rightChild

        elif i == ')':
            currentTree = pStack.pop()
            print 'StackSize: {}, root: {}      iteration(pop)'.format(
                pStack.size(), currentTree.getRootVal(), i)

        else:
            raise ValueError
    print 'eTee root:  {} '.format(eTree.getRootVal())
    return eTree
Ejemplo n.º 15
0
def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            if operandStack.size()>=2:
                operand2 = operandStack.pop()
                operand1 = operandStack.pop()
                result = doMath(token,operand1,operand2)
                operandStack.push(result)
            else:
                return 'Error: Unmatched quantity of operators and operands'
    return operandStack.pop()
Ejemplo n.º 16
0
def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        #print(token + ', size: ' + str(operandStack.size()))
        if is_int(token):
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)

    if (operandStack.size() == 0):
        return None
    else:
        return operandStack.pop()
Ejemplo n.º 17
0
 def f_to_m(cur_list):  # 前转中缀
     """
     :cur_list: list
     """
     temp = []
     temp2 = []
     s = Stack()
     list = [str(i) for i in cur_list]
     print(list)
     for par in list:
         if par in "+-*/":  # 遇到运算符则入栈
             s.push(par)
         else:  # 为数字时分两种情况:
             if s.peek() in '+-*/':  # 栈顶为运算符
                 s.push(par)  # 数字入栈
             else:  # 当前栈顶为数字
                 while (not s.isEmpty()) and (
                         not s.peek() in '+-*/'):  # 若栈不空,且当前栈顶为数字,则循环计算
                     shu = s.pop()  # 运算符前的数字出栈
                     fu = s.pop()  # 运算符出栈
                     if fu == '+' or fu == '-':
                         if s.size() == 0:  # 最后一次运算不需要括号,无论什么运算符
                             par = shu + fu + par
                             break
                         par = '(' + shu + fu + par + ')'  # 计算
                     else:  # 乘除不需要括号
                         par = shu + fu + par  # 计算
                 s.push(str(par))  # 算式入栈
     list1 = (str(s.pop()))  # 用列表存新的算式
     for i in list1:
         if i in '+-*/()':
             if len(temp2) == 0:
                 temp.append(i)
             else:
                 temp.append(int(''.join(temp2)))
                 temp2.clear()
                 temp.append(i)
         else:
             temp2.append(i)
     if len(temp2) != 0:
         temp.append(int(''.join(temp2)))
     return temp  # 返回最终算式
Ejemplo n.º 18
0
class Queue:
    def __init__(self):
        # self.items = []
        self.inbox = Stack()
        self.outbox = Stack()

    def enqueue(self, item):
        self.inbox.push(item)

    def dequeue(self):
        assert (self.outbox.isEmpty())
        while not self.inbox.isEmpty():
            self.outbox.push(self.inbox.pop())
        res = self.outbox.pop()
        while not self.outbox.isEmpty():
            self.inbox.push(self.outbox.pop())
        return res

    def isEmpty(self):
        return self.size() == 0

    def size(self):
        return self.inbox.size()
Ejemplo n.º 19
0
def postfix_to_infix(postfixexpr):
    infixStack = Stack()
    tokenList = postfixexpr.split()
    print(tokenList)
    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" or token in "0123456789":
            infixStack.push(token)
        else:
            if infixStack.size() < 2:
                print("Error! Invalid Input")
                exit(-1)
            else:
                operand2 = infixStack.pop()
                operand1 = infixStack.pop()
                infixStack.push(
                    ("( " + operand1 + " " + token + " " + operand2 + " )"))
    output = ""
    output += infixStack.pop()
    if infixStack.isEmpty():
        return output
    else:
        print("Error! Invalid Input!")
        exit(1)
Ejemplo n.º 20
0
def doWhileToWhile(fo, file):
    in_file = []

    with fo as f:
        in_file = f.readlines()

    out_file = []

    exist_while = 1
    lookupDo = "do{"
    lookupWhile = "}while"
    lookupReturn = "return"
    z = 0
    while exist_while:
        out_file = []
        print str(z) + "dsds"
        z = z + 1
        start = ""
        end = ""
        start_index = -1
        end_index = -1
        st = Stack()
        st_index = Stack()
        i = 0
        for i in range(len(in_file)):
            print in_file[i]
            if lookupReturn in in_file[i]:
                continue
            if lookupDo in in_file[i]:
                st.push(in_file[i])
                print st.size() + 10000000
                st_index.push(i)
            elif lookupWhile in in_file[i]:
                if st.size() == 1:
                    start = st.peek()
                    start_index = st_index.peek()
                    print in_file[i]
                    st.pop()
                    st_index.pop()
                    end = in_file[i]
                    end_index = i
                    break
                else:
                    st.pop()
                    st_index.pop()

        if start_index == end_index or start_index == -1 or end_index == -1:
            if not st.isEmpty():
                print "The code given as input is wrong. Please, check and try again.\n Line No:" + st.top(
                )
            break

        end = end.replace("}while", "while")
        end = end.replace(";", "")
        end = end + "{\n"

        print str(end_index) + "ss" + str(start_index)
        for i in range(len(in_file)):
            if i != start_index and i < end_index:
                out_file.append(in_file[i])

        for i in range(len(in_file)):
            if i == start_index:
                out_file.append(end)
            elif i == end_index:
                out_file.append("}\n")
            elif i > start_index:
                out_file.append(in_file[i])

        in_file = []
        in_file = out_file

    print in_file
    with file as f:
        f.writelines(in_file)
    return
Ejemplo n.º 21
0
    def isEmpty(self):
        return self.items == []

    def push(self, item):
        return self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items) - 1]

    def size(self):
        return len(self.items)


s = Stack()

print(s.isEmpty())
print(s.size())
s.push(10)
s.push('AJAY')
s.push("hi this is Sanjay")
print(s.peek())
print(s.size())
s.pop()
s.pop()
print(s.peek())
print(s.size())
print(s.isEmpty())
from pythonds.basic.stack import Stack

s = Stack()

s.push(33)
print(s.size())
Ejemplo n.º 23
0
s_input.push(('z', ''))
for i in range(0, inp.__len__()):
    #print(inp[inp.__len__()-1-i])
    s_input.push(inp[inp.__len__() - 1 - i])

s_parsser = Stack()
s_parsser.push((0, ''))

map_action = table_action()
map_goto = table_goto()
follow = follows()

alaki = Stack()

while True:
    if s_parsser.size() >= 13:
        char = ''
        str = ''
        alaki.push(s_parsser.peek())
        s_parsser.pop()
        alaki.push(s_parsser.peek())
        s_parsser.pop()
        char = alaki.peek()[0]
        if char == 'l':
            for j in range(5):
                alaki.push(s_parsser.peek())
                s_parsser.pop()
                alaki.push(s_parsser.peek())
                s_parsser.pop()
                str = str + alaki.peek()[0]
            if not str.__eq__('jFibE'):
Ejemplo n.º 24
0
        return self.items[len(self.items) - 1]

    def size(self):
        return len(self.items)


from pythonds.basic.stack import Stack

s = Stack()

print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())

print("")
print("Sum numbers in a list")
numlist = [5, 6, 7]
print(numlist)
print(sum(numlist))

print("")
print("Reversing text using Stack")
text = "The Quick Brown Fox Jumps Over The Lazy Dog"
Ejemplo n.º 25
0
	return (stack)



def op_chacksigverify(stack):
	stack = op_verify(stack)
	stack = op_checksig(stack)
	return (stack)

def hash160(data):
	val = hashlib.sha256(data).digest()
	h = hashlib.new('ripemd160')
	h.update(val)
	return (h.digest())

def op_hash160(stack):
	val = hash160(stack.pop())
	stack.push(val)
	return (stack)





if __name__ == '__main__':
	stack = Stack()
	stack.push(b"kek")
	print(stack.size())
	stack = op_hash160(stack)
	print(stack.size())
Ejemplo n.º 26
0
def build_tree_expression(elements):
    stack = Stack()
    tree = BinaryTree('')
    if len(elements) == 1:
        tree.setRootVal(elements[0])
        return tree
    stack.push(tree)
    for i in range(len(elements)):
        if (elements[i] == '(') or (i == 0):
            tree.insertLeft('')
            if elements[i] == '(':
                stack.push("(")
            stack.push(tree)
            tree = tree.getLeftChild()
            if elements[i] != '(':
                tree.setRootVal(elements[i])
                parent = stack.pop()
                tree = parent
        elif elements[i] not in ['+', '-', '*', '/', ')']:
            tree.setRootVal(elements[i])
            parent = stack.pop()
            tree = parent
        elif elements[i] in ['+', '-', '*', '/']:
            sign = elements[i]
            if tree.getRootVal() in ['+', '-', '*', '/']:
                if sign in ['+', '-'] or elements[i - 1] == ')':
                    temp = BinaryTree('')
                    parent = stack.pop()
                    if stack.size() == 0:
                        temp.insertLeft(parent)
                        parent = temp
                        tree = parent
                        stack.push(parent)
                    elif parent == "(":
                        temp.insertLeft(tree)
                        parent = stack.pop()
                        parent.insertRight(temp)
                        stack.push(parent)
                        stack.push("(")
                        tree = parent.getRightChild()
                    else:
                        temp.insertLeft(tree)
                        parent.insertRight(temp)
                        stack.push(parent)
                        tree = parent.getRightChild()
                elif sign in ['*', '/']:
                    rChild = tree.getRightChild()
                    rChild.insertLeft(rChild.getRootVal())
                    tree = rChild
            tree.setRootVal(elements[i])
            tree.insertRight('')
            stack.push(tree)
            tree = tree.getRightChild()
        elif elements[i] == ')':
            parent = ""
            while parent != "(":
                parent = stack.pop()
                if parent == "(":
                    tree = stack.pop()
            stack.push(tree)
        if i + 1 == len(elements):
            for j in range(stack.size()):
                parent = stack.pop()
                tree = parent
    return tree
Ejemplo n.º 27
0
def cToCvc4(name, fo, file, no_arr):

    #search for main function
    lookup = 'main'
    start = -1

    for num, line in enumerate(fo, 1):
        if lookup in line:
            start = num
            break

    #abort if main function not found
    if start == -1:
        sys.exit("Aborting!!!\nError : main() function is missing")

    fo.seek(0)

    l = fo.readlines()

    st = Stack()

    st_assert = 0

    for i in range(start, len(l)):
        l[i] = bothSideStrip(l[i])
        if not l[i] or l[i].startswith('{'):
            continue
        l[i] = l[i].replace("==", " = ")
        l[i] = l[i].replace("&&", " AND ")
        l[i] = l[i].replace("&", " AND ")
        l[i] = l[i].replace("false", " FALSE ")
        l[i] = l[i].replace("true", " TRUE ")
        print l[i]
        if l[i].startswith('int') or l[i].startswith(
                'char') or l[i].startswith('bool'):
            no_arr = defDataType(l[i], file, no_arr)
        elif l[i].startswith('if'):
            cond = find_between(l[i], "(", ")")
            st.push('i')
            if st_assert == 0:
                file.write("ASSERT ")
                st_assert = 1
            file.write("IF " + cond + " THEN\n")
            continue
        elif l[i].startswith('for'):
            f = find_between(l[i], "(", ")")
            f1 = f.split(";")
            init = f1[0]
            cond = f1[1]
            bool_cond = ""
            var = "x"
            print "c " + cond
            if "<" in cond or ">" in cond or "=" in cond:
                print cond + "dk"
                i1, i2, c1, c2, var = for_cond_init(cond, init)
                bool_cond = i1 + " " + c1 + " " + var + " AND " + cond
            else:
                bool_cond = cond
            st.push('f')
            if st_assert == 0:
                file.write("ASSERT ")
                st_assert = 1
            file.write("FORALL ( " + var + " : INT) : " + bool_cond + " =>\n")
            continue
        elif l[i].startswith('while'):
            cond = find_between(l[i], "(", ")")
            st.push('f')
            var = "x"
            if st_assert == 0:
                file.write("ASSERT ")
                st_assert = 1
            file.write("FORALL ( " + var + " : INT) : " + cond + " =>\n")
            continue
        elif l[i].startswith('}else'):
            st.pop()
            file.write(" ELSE\n")
            st.push('e')
            continue
        elif l[i].startswith('}'):
            if not st.isEmpty():
                if st.peek() == 'f':
                    st.pop()
                    l[i + 1] = bothSideStrip(l[i + 1])
                    if not st.isEmpty():
                        if (not l[i + 1].startswith('}')) and (
                                st.peek() == 'f' or st.peek() == 'i'
                                or st.peek() == 'e'):
                            print st.peek()
                            sys.exit("This is not supported by this Parser")

                        if l[i + 1].startswith('}') and (st.peek() == 'f'
                                                         or st.peek() == 'i'
                                                         or st.peek() == 'e'):
                            continue

            if not st.isEmpty():
                if st.peek() == 'e':
                    st.pop()
                    file.write(" ENDIF")

        elif l[i].startswith('return'):
            break
        else:
            if st_assert == 0:
                file.write("ASSERT ")
            file.write(l[i][:-1])
        print st.size()
        if st.isEmpty():
            file.write(" ;\n\n")
            st_assert = 0
        else:
            l[i + 1] = bothSideStrip(l[i + 1])
            if l[i + 1].startswith('}else') or l[i + 1].startswith('}'):
                print 'w'
                continue
            else:
                file.write(" AND\n")
        print i
    return no_arr
Ejemplo n.º 28
0
from pythonds.basic.stack import Stack

#print('请输入汉诺塔的层数')
#N = int(input())
N = 3
global A, B, C, step
A = Stack()
B = Stack()
C = Stack()
x = []
step = 0
lst = list(range(1, N + 1))
lst.reverse()
for i in lst:
    A.push(i)
print(A.size())


def tower(s1, s2, s3, N=-1):  # 汉诺塔算法,借助s2,将s1的N层移动到s3
    global step
    if (N == -1):
        N = s1.size()
    if (N == 0):
        return
    elif (N == 1):  # 判断栈的深度,如果栈深为1,则一次简单移动即可;若大于1,则需要进行递归操作
        #move(s1, s3)
        moveDisk(s1, s3)
        s3.push(s1.pop())
        print('%-20s %-20s %-20s' %
              (A.size(), B.size(), C.size()))  # 为了方便展示结果,输出语句做了调整
        step += 1
Ejemplo n.º 29
0
from pythonds.basic.stack import Stack

s = Stack()

assert(s.isEmpty())
s.push(4)
s.push('dog')
assert(s.peek() is 'dog')
s.push(True)
assert(s.size() is 3)
assert(s.isEmpty() is False)
s.push(8.4)
assert(s.pop() is 8.4)
assert(s.pop() is True)
assert(s.size() is 2)