#!/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!
#!/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+