-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidatingCpp.py
More file actions
executable file
·44 lines (38 loc) · 1.51 KB
/
validatingCpp.py
File metadata and controls
executable file
·44 lines (38 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
__author__ = "streethacker"
#/usr/bin/python
#-*- coding:utf-8 -*-
# Data Structures and Algorithms Using Python
# CHAPTER 7: Stacks
# Listing 7.3: validatingCpp.py
from lliststack import Stack
def isValidSource(srcFile):
"""
The function accepts a file object, which we assume was previously opened and contains C++
source code.The file is scanned one line at a time and each line is scanned one character
at a time to determine if it contains properly paired and balanced delimiters.
"""
s = Stack()
for line in srcFile:
for token in line:
if token in "{[(":
# if token is one of the opening delimiters it should be pushed
# into the stack.
s.push(token)
# if token is one of the closing delimiters it should be checke by
# the following steps.
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()
if __name__ == "__main__":
with open("/home/streethacker/maxMsub/maxMsub.cpp", "r") as srcFile:
if isValidSource(srcFile):
print "This is a valid C++ file."
else:
print "This is an invalid C++ file, cause delimiters are not balanced."