Sunday, October 10, 2010

findPattern() Python Code...not executing correctly?

Programmer Question

Hi all, 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 lettern 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!



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails