Created
January 26, 2022 21:57
-
-
Save les-peters/c8f0a98a8caa57f56abcc8e98cf609b3 to your computer and use it in GitHub Desktop.
Palindrome file search
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
question = """ | |
You are given three files named first_page.txt, second_page.txt, and third_page.txt | |
with the occurrence of at least one palindrome in each of them. Write a script to find the following: | |
The exact number of palindromes in each file. | |
The line numbers of the palindromes in each file. | |
""" | |
import re | |
# originally from 2021-08-16: Palindrom Hunt | |
def palTest(pal, str): | |
pal_double = re.compile(r'((.)' + pal + r'(\2))') | |
pal_single = re.compile(r'((.)' + pal + r'(\2))') | |
double_test = pal_double.search(str) | |
if double_test: | |
if str == pal: | |
print('equal') | |
return double_test.group(1) | |
else: | |
return double_test.group(1) | |
else: | |
single_test = pal_single.search(str) | |
if single_test: | |
print('single') | |
return single_test.group(1) | |
else: | |
return False | |
def pSubstring(input): | |
pals = {} | |
out = palTest('', input) | |
# start with double center | |
while out: | |
next = palTest(out, input) | |
if out == input: | |
break | |
if next: | |
out = next | |
else: | |
break | |
if out: | |
pals[out] = 1 | |
for char in input: | |
out = palTest(char, input) | |
if out: | |
pals[out] = 1 | |
for pal in pals.keys(): | |
if pal and len(pal) >= 4: | |
return(pal) | |
filenames = [ './2022/first_page.txt', './2022/second_page.txt', './2022/third_page.txt'] | |
for filename in filenames: | |
with open(filename, newline='') as lines: | |
palindrome_count = 0 | |
linenbr = 0 | |
for line in lines: | |
linenbr += 1 | |
palindrome = pSubstring(line) | |
if palindrome: | |
palindrome_count += 1 | |
print(filename + ":" + str(linenbr) + " " + palindrome) | |
print(filename + " has " + str(palindrome_count) + " palindrome(s)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment