Skip to content

Instantly share code, notes, and snippets.

@basicxman
Created August 19, 2011 05:02
Show Gist options
  • Select an option

  • Save basicxman/1156084 to your computer and use it in GitHub Desktop.

Select an option

Save basicxman/1156084 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import re
import string
def process_string_re(line):
"""Removes alphanumeric characters using regular expressions."""
return re.sub(r'[a-z0-9]', '', line)
def process_string(line):
"""Removes alphanumeric characters without regular expressions."""
s = line
for char in range(0, 9) + string.lowercase[:26]:
s = s.replace(char, "")
return s
def check_balance(line):
"""Checks if a line is balanced."""
parenthesis = ["{}", "[]", "()"]
s = process_string_re(line)
for match in parenthesis:
s = s.replace(match, "")
return len(s) == 0
input_data = open('./input.txt', 'r').read().split("\n")
for line in input_data:
if len(line) == 0: continue
if check_balance(line):
print "balanced"
else:
print "not balanced"
@basicxman
Copy link
Author

File.readlines("input.txt").each { |line| puts line.chomp.gsub(/[a-z0-9]/, "").gsub("{}", "").gsub("[]", "").gsub("()", "").length == 0 ? "balanced" : "not balanced" }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment