使用堆栈和文件读取来平衡python中的C样式代码

时间:2019-07-04 15:56:35

标签: python

我想我设法使它与堆栈一起工作,但不确定。但是我需要平衡文本文件中的C样式代码。我不知道堆栈是否正确。

class stack:
    def __init__(self):
        self._items = []

    def isEmpty(self):
        return self._items == []

    def push(self, item):
        self._items.append(item)

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

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

open_list = ["[","{","("]
close_list = ["]","}",")"]
count = 0
stack = []
fileOpen = input("Please enter the name of the file with C style code - should end in .txt ")
my_file = open(fileOpen + ".txt","r")
the_record = my_file.readlines()
count = count + 1
for i in the_record:
    the_record = the_record[:-1]
    if i in open_list:
        stack.append(i)
    elif i in close_list:
        pos = close_list.index(i)
        if ((len(stack) > 0) and
            (open_list[pos] == stack[len(stack)-1])):
            stack.pop()
        else:
            print("Line", count, "is Not OK wrt bracket matching")
if len(stack) == 0: 
    print("Line", count, "is OK")

在文本文件中

asdasdas([])
adas[](

我希望显示所有结果,如:

Line 1 is Ok
Line 2 is Not Ok

只有第1行出现:

Line 1 is Ok

1 个答案:

答案 0 :(得分:0)

if (!($result=mysqli_query($conn, $sql))) { die("Could not show the required data" . mysqli_error($conn));} elseif (mysqli_num_rows($result) > 0) { while($result2=mysqli_fetch_array($result)) {echo '<tr> <td>'.$result2["Asset_name"].'</td> <td>'.$result2["Classification"].'</td> <td>'.$result2["Tag"].'</td> <td>'.$result2["Department"].'</td> <td>'.$result2["Review_date"].'</td> <td>'.$result2["Responsible"].'</td> </tr>'; } 变量是的列表。因此the_record总是一行,并且iasdasdas([])都不属于adas[](open_list,因此close_list循环不执行任何操作。当退出时,没有向<{>} 添加任何元素,因此forstack被打印。

len(stack) == 0

您需要一个double for循环,一次在一行上,一次在一行上的字符上:

Line 1 is OK