Skip to content

Instantly share code, notes, and snippets.

@prail
Last active April 9, 2023 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prail/c1914d0c7f10348d99656251e4ed7409 to your computer and use it in GitHub Desktop.
Save prail/c1914d0c7f10348d99656251e4ed7409 to your computer and use it in GitHub Desktop.
Centers banner comments in CS227 programs
#!/usr/bin/python3
"""
This script finds all banner comments in a Howell (CS227) program and perfectly
centers them, so you won't get any points off on your programs for that.
Prints out the contents of the program just to be safe.
Andrew Teesdale, Jr. (f40c40.com)
"""
import sys
MAX_WIDTH = 72
BANNER_MARKER = "/"+ ("*" * (MAX_WIDTH - 2)) + "/"
# Banner matcher states
NONE_MATCHED = 0
OPEN = 1
CLOSE = 2
if __name__ == "__main__":
if len(sys.argv) != 2:
print("error: Provide at least one file to center")
sys.exit(1)
f = open(sys.argv[1], "r")
line_no = 0 # The current line being read
banner_lines = [] # The lines center properly
match_state = NONE_MATCHED
# The current state of the banner matcher
banner_count = 0
# Loop marking banner comments and tracking which lines their content
# is on
lines = f.readlines()
for line in lines:
# Banner comment state machine
if line.strip() == BANNER_MARKER:
if match_state == NONE_MATCHED:
match_state = OPEN
elif match_state == OPEN:
match_state = CLOSE
banner_count += 1
elif match_state == CLOSE:
match_state = OPEN
else:
pass
elif match_state == OPEN:
if banner_count >= 3:
lines[line_no] = \
"/*" + lines[line_no][2:-3].strip().center(MAX_WIDTH - 4) + "*/\n"
else:
pass
line_no += 1
print("".join(lines))
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment