Last active
February 17, 2019 00:08
-
-
Save jaizon2000/a7879082d3a025797c312930e235eaad to your computer and use it in GitHub Desktop.
# Exercise 32: Write a version of a palindrome recognizer that accepts a file name from the user, reads each line, and prints the line to the screen if it is a palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A but tuba | |
radar | |
raddar | |
A car, a man, a maraca | |
A Santa at Nasa | |
Hello, World | |
Ah, Satan sees Natasha! | |
Aibohphobia | |
Air an aria. | |
Al lets Della call Ed Stella. | |
alula |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def is_palindrome(fname): | |
f = open(fname) | |
line = f.readline().lower() | |
while line != "": | |
i = 0 | |
j = len(line.strip()) - 1 # -1 cuz index starts at 0 | |
while i <= j: | |
# Read from LEFT | |
while not line[i].isalpha() and i != j -1: # j-1 so it doesn't add 1 to i before breaking loop | |
i += 1 | |
# Read from RIGHT | |
while not line[j].isalpha() and j != i: | |
j -= 1 | |
#print(i, line[i], "|", j, line[j]) # check to visualize | |
if line[i] == line[j]: | |
i += 1 | |
j -= 1 | |
else: | |
i, j = j, i | |
if i >= j: # see line 16, it adds to val before break >> go back before index was +/- | |
i -= 1 | |
j += 1 | |
# BOOL Shortcuts | |
line_not_empty = len(line.strip()) != 0 | |
is_alpha = line[i].isalpha() or line[j].isalpha() | |
both_is_alpha = line[i].isalpha() and line[j].isalpha() | |
if (not is_alpha or line[i] != line[j]) and line_not_empty: | |
print("| False |", line.strip()) | |
if both_is_alpha and line[j] == line[i] and line_not_empty: | |
print("| True |", line.strip()) | |
# READ next line when i <= j | |
line = f.readline().lower() | |
f.close() |
is_palindrome() - original w/ dictionaries and list
d = {}
for word in lines:
word = list(word.lower())
if len(word) == 0:
lines.remove('\n')
for char in word:
if char not in "abcdefghijklmnopqrstuvwxyz":
word.remove(char)
print(word)
d["".join(word)] = "".join(reversed(word))
i = 0
for key in d.keys():
if d[key] == key:
print(txt[i].rstrip())
i += 1
else:
i += 1
print(d)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is_palindrome() using sting checkup