Python: implement a function duplicate() that takes as input a string and the na
ID: 657178 • Letter: P
Question
Python:
implement a function duplicate() that takes as input a string and the name of a file in the current working directory and returns true if the file contains duplicate words and false otherwise.
this is what I have, and I keep getting false on a file that definitely has duplicate words
def duplicate(filename):
infile = open(filename, 'r')
content = infile.read()
infile.close()
table = str.maketrans('!,.:;?',6*' ')
content = content.translate(table)
content = content.lower()
wordList = content.split()
for i in wordList:
wordList.count(i)
if wordList.count(i) > 1:
return True
else:
return False
I've tried several variations on this and I can seem to get why it's not working.
I think I just figured it out, what was missing was in bold I think
Explanation / Answer
def has_duplicate_words(filename): with open(filename, 'r') as f: words = set() for line in f.readlines(): lineWords = line.split() for word in lineWords: if word in words: return True words.add(word) return False
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.