In: Computer Science
4.31 Implement function duplicate() that takes as input the name (a string) of a file in the current directory and returns True if the file contains duplicate words and False otherwise. duplicate('Duplicates.txt') True duplicate('noDuplicates.txt') False
Please solve using Python Language and without using str.maketrans please. Just simple programming, Thank youuuuu!!!!!
# defining a function duplicate that will check if the file contains duplicates words or not
def duplicate(fileName):
# opening the text file in read mode
f = open(fileName, 'r')
# create an empty dictionary
d={}
# loop through each line of the file
for line in f:
# take each word of the line
for word in line.split(" "):
# to find the frequency of each word in the dictionary
d[word] = d.get(word,0)+1
#loop through each value of dictionary d and if the value of any key is greater then 1 then return True
for value in d.values():
if value>1:
return True
#return False
return False
# calling duplicate() function from 'main'
if __name__ == '__main__':
if duplicate("Duplicates.txt"):
print("Duplicates")
else:
print("Not Duplicates")
if duplicate("noDuplicates.txt"):
print("Duplicates")
else:
print("Not Duplicates")
python file
John David Rey Ronald Rey David
Have a great day
Duplicates.txt file
David John Rey Ronald Smith
Keep learning and growing
noDuplicates.txt
Sample Input and Output:
Duplicates
Not Duplicates
Code explainations:
Here I have implemented the duplicate() function that will accept a filename as an input and then it will open the file in read mode. Then it will create an empty dictionary to hold the key:value pair.
Now it will fetch each line from the input file and then from each line it will fetch each word.
Now it will find the frequency of each word in the dictionary as
d[word] = d.get(word,0)+1
Here get() method will return the value of given key if present and if not present it will return 0.
Simply we have added 1 to it to increment the count of each word in dictionary
Finally it will check for all the values of dictionary using d.values() method to check if any value in dictionary is greater then 1 that means that word is duplicate in the input file. So we returns True.
If there is not duplicates then simply we return False.
Code screenshot: