Python 使用堆栈验证C文件括号是否匹配

#!/usr/bin/python 
# -*- coding: utf-8 -*-

'''
Created on 2015-1-29
@author: beyondzhou
@name: test_balancedelimiter.py
'''

# Implementation of the algorithm for validating balanced brackets in a C++ source file
from mystack import LinkListStack

def isValidSource(srcfile):
    s = LinkListStack()
    for line in srcfile:
        for token in line:
            if token in "{[(":
                s.push(token)
            elif token in "}])":
                if s.isEmpty():
                    return False
                else:
                    left = s.pop()
                    if (token == "}" and left != "{") or \
                       (token == "]" and left != "[") or \
                       (token == ")" and left != "("):
                        return False

    return s.isEmpty()

def test_balancedelimiter():
    
    # read c file
    filename = r'E:\Pica8\eclipse\validC.c'
    fobj = open(filename, 'r').readlines()
    
    for line in fobj:
        print line.strip()
    print 
        
    if isValidSource(fobj):
        print '%s is valid c file!' % filename
    else:
        print '%s is no valid c file!' % filename
        
    # read c file
    filename = r'E:\Pica8\eclipse\notvalidC.c'
    fobj = open(filename, 'r').readlines()
    
    for line in fobj:
        print line.strip()
    print 
       
    if isValidSource(fobj):
        print '%s is valid c file!' % filename
    else:
        print '%s is no valid c file!' % filename
    
if __name__ == "__main__":
    test_balancedelimiter()

int sumList( int theList[], int size )
{
int sum = 0;
int i = 0;
while( i < size ) {
sum += theList[ i ];
i += 1;
}
return sum;
}

pop item: [
pop item: (
pop item: (
pop item: [
pop item: {
pop item: {
E:\Pica8\eclipse\validC.c is valid c file!
int sumList( int theList[], int size )
{
int sum = 0;
int i = 0;
while( i < size ) {
sum += theList[ i ];
i += 1;
}
return sum;

pop item: [
pop item: (
pop item: (
pop item: [
pop item: {
E:\Pica8\eclipse\notvalidC.c is no valid c file!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值