Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

USING PYTHON Write a function named lineIndex that takes a file name, fName, as

ID: 3833638 • Letter: U

Question

USING PYTHON

Write a function named lineIndex that takes a file name, fName, as a parameter and returns a dictionary, d, that indexes the words in fName by line number, with the first line in fName being numbered 0.

Each word in fName should be a key in the returned dictionary d, and the corresponding value should be a list of the line numbers on which the word occurs. A line number should occur no more than one time in a given list of line numbers.

The file fName contains only upper and lower case letters and white space. Capital and lower case letters are different. That is, 'You' is not the same word as 'you'.

Explanation / Answer

def lineIndex(fName):
d = {}
with open(fName, "r") as fh:
i = 0
for line in fh:
words = line.split()
for word in words:
if word in d:
if i in d[word]:
continue
else:
d[word].append(i)
else:
d[word] = [i]
i += 1
return d

print(lineIndex("input.txt"))

# code link: https://paste.ee/p/K857I