In: Computer Science
Python
English algorithm explanation
Write a program that asks the user for the name of a file in the
current directory. Then, open the
file and process the content of the file.
1)If the file contains words that appear more than once, print “We
found duplicates.”
2)If the file does not contain duplicate words, print “There are no
duplicates.”
Explanation:
Here is the code which asks for the filename from the user and then creates a list of words and then each word's count is checked inside the list.
If any word is repeated, then we print "We found duplicates."
Otherwise, we print "There are no duplicates."
file.txt used:
hi how are you hi
Code:
filename = input("Enter filename: ")
f = open(filename, 'r')
words = f.read().strip().split(" ")
duplicates = False
for word in words:
if(words.count(word) > 1):
duplicates = True
if(duplicates==True):
print("We found duplicates.")
else:
print("There are no duplicates.")
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!