my homework assignment was to: “write a function called findPattern() which accepts two strings as parameters, a filename and a pattern. The function reads in the file specified by the given filename and searches the file’s contents for the given pattern. It then returns the line number and index of the line where the first instance of this pattern is found. If no match is found, your function should return -1 for both the line number and index.”
I was fairly certain that my code was accurate until it would execute the first commands and then just ignore the rest of the code. I tried a couple different ways of writing it, but all three yielded the result of…not working.
I’ll post the two relevant codes below:
Code 1:
def findPattern (filename, pattern):
f=open(filename)
linecount = 0
lettercount = 0
for line in f:
lineCount +=1
for letter in range(len(line)):
if line(letter)==pattern:
letterCount+=1
return[lineCount,line]
return "Did not find " + pattern
Code 2:
print
filename = raw_input("Enter a file name: ")
pattern = raw_input("Enter a pattern: ")
def findPattern (filename,pattern):
f=open(filename)
lineCount = 0
letterCount = 0
for line in f:
lineCount +=1
for letter in range(len(line)):
if line(letter)==pattern:
letterCount+=1
print ("Found pattern " + pattern + " at " + str((lineCount, letter)))
I think code 2 would be more likely to work but it isn’t yielding any results. Any input would be appriciated.
-Thanks!
Your variable names are misspelled:
linecountvs.lineCount,letternvs.letter. Python doesn’t always warn against this type of error. If this is just a copying error, thenline(letter)is the error: an index is given by[]. What kind of pattern are you searching for, a single character or a string?line[letter]will only return a single character.Next time, please post not only the code and that it gives an error, but also what kind of error. Most Python errors result in exceptions being thrown (such as
TypeError), which can tell you (and us) a lot about what’s been going wrong.