palindrome | ˈpalənˌdrōm | noun a word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.
The 'palindrome_finder' project includes 3 files: a dictionary file named 'dict.txt', a dictionary loader file named 'load_dictionary.py', as well as the main file (that recognizes palindromes within the dictionary file) named 'palingram_finder.py'.
As soon as I run the file, I receive the following error:
Traceback (most recent call last):
File "/Users/cheshirecat/Desktop/python_projects/palingram_finder/palingram_finder.py", line 16, in <module>
if word[::-1] == word and len(word) >= 3:
~~~~^^^^^^
TypeError: 'builtin_function_or_method' object is not subscriptable
[Finished in 58ms with exit code 1]
For context, here are the two python files.
load_dictionary
import sys
def load(file):
"""Open a text file and return a list of lowercase strings"""
try:
with open(file) as in_file:
loaded_txt = in_file.read().strip().split()
loaded_txt = [x.lower for x in loaded_txt]
return loaded_txt
except IOError as e:
print("{}\n Error opening {}. Terminating program.".format(e, file), file=sys.stderr)
sys.exit(1)
palingram_finder
from load_dictionary import load
from pprint import pp
word_list = load('./dict.txt')
palindrome_list = []
for word in word_list:
if word[::-1] == word and len(word) >= 3:
palindrom_list.append(word)
print("Number of palindromes found: {}\n\n".format(len(palindrome_list)))
pp(palindrome_list)
Attempts at a fix: I tested a simplified version of the palindrome recognition code using the built in python shell as shown below.
>>> word_list = ['betrayal', 'enigma', 'tenet', 'multitude', 'did']
>>>
>>> palindrome_list = []
>>>
>>> for word in word_list:
... if len(word) >= 3 and word[::-1] == word:
... palindrome_list.append(word)
...
>>> palindrome_list
['tenet', 'did']
>>> exit()
Since it worked, I decided that the problem was with the way the dictionary was being loaded.
This is where I get stuck, for when I load the dictionary within Sublime text editor's shell in the same manner as load_dictionary.py
, I am given a list of strings. Shouldn't it work, then?
The error you're getting is due to this line in load_dictionary.py
file:
loaded_txt = [x.lower for x in loaded_txt]
You are not calling x.lower
, just referencing it. Call it as a method:
loaded_txt = [x.lower() for x in loaded_txt]
This will solve your issue 😊.