Question

In: Computer Science

Write code in Python that does the following : An anagram is when the order of...

Write code in Python that does the following : An anagram is when the order of a word can be changed to create a new word (evil,
live, and vile for example). Using the dictionary provided, find all of the anagram groups.
Which words contain the most anagrams? How large is this group? Here is another example:
Alert, alter, and later have 3 in their group. Use the provided dict.txt as your word list,
solution must also finish in less than a minute.

* I know there is no dict.txt file to use here..

file = open("dict.txt", "r", encoding="utf8")

*looking for a way to sort through the file and group anograms together

*output the groups from largest to smallest (if there is only a single word in a group, no need to display)
file.close()

Solutions

Expert Solution

To solve this program, I am assuming the dict.txt file contains the words one in each line as specified in the question. A sample dict file screenshot is added here, on which I will be working here-

Here the anagram groups are-

  1. [evil, live, vile]
  2. [lump,plum]
  3. [eat,tea]
  4. [alter,later,alert]

The python code for opening this file and finding all the anagram groups is given below-

from collections import defaultdict

file = open("dict.txt", "r", encoding="utf8")

#Store the file contents in a list
words = []
for line in file.readlines():
    words.append(line.strip())

#Close the file
file.close()

#Create default dictionary of list type
d = defaultdict(list)

for word in words:
    d[str(sorted(word))].append(word)

#Extract the anagram groups
groups = d.values()

#Remove the group whose length is 1
groups = [group for group in groups if len(group)>1]

#Sort the groups according to their length from largest to smallest
groups = sorted(groups, key = len, reverse = True)

print(groups)

Explanation -

  • First, we open the file dict.txt and store all the words in it in a list named as words.
  • Then the file is closed.
  • We create a defaultdict of type len. A defaultdict is used when we want to refer to a key that is already not present in the dictionary. If such a key is accessed, a new key gets created and value is added. Here, the key is a string value and values are lists.
  • We traverse through the words and store them in the dictionary. This is an important step. The working is explained through an example. Consider the words - [ate,eat,tea] . Here, d[str(sorted(word))] becomes the key. So, in this case, always aet will become the key and its values will be the list [ate, eat, tea]. In this way, all the anagrams will be grouped together.
  • Then we extract a list of lists by taking all the values of the dictionary.
  • Next, we iterate over this list and remove all the lists whose length is 1, i.e. they are not anagrams with any other word.
  • Then, we sort the group of words, through Python sorted function, where key=len, i.e. sorting takes place by the length of the list, and reverse=True means list is sorted from largest to smallest.

Code Screenshot - for indentation

OUTPUT -

Keep the dict.txt in the same folder as the Python program


Related Solutions

Write the following Python code: A string X is an anagram of string Y if X...
Write the following Python code: A string X is an anagram of string Y if X can be obtained by arranging all characters of Y in some order, without removing any characters and without adding new characters. For example, each of the strings "baba", "abab", "aabb" and "abba" is an anagram of "aabb", and strings "aaab", "aab" and "aabc" are not anagrams of "aabb". A set of strings is anagram-free if it contains no pair of strings which are anagrams...
Write the following Python script: Problem Statement A string X is an anagram of string Y...
Write the following Python script: Problem Statement A string X is an anagram of string Y if X can be obtained by arranging all characters of Y in some order, without removing any characters and without adding new characters. For example, each of the strings "baba", "abab", "aabb" and "abba" is an anagram of "aabb", and strings "aaab", "aab" and "aabc" are not anagrams of "aabb". A set of strings is anagram-free if it contains no pair of strings which...
Write a Python function with prototype “def anagramdictionary(wordlist):” that will return an “anagram dictionary” of the...
Write a Python function with prototype “def anagramdictionary(wordlist):” that will return an “anagram dictionary” of the given wordlist  An anagram dictionary has each word with the letters sorted alphabetically creating a “key”.
Please provide Python code that does the following: 3) Write a program that takes a string...
Please provide Python code that does the following: 3) Write a program that takes a string as input, checks to see if it is comprised entirely of letters, and if all those letters are lower case. The output should be one of three possible messages: Your string is comprised entirely of lower case letters. Your string is comprised entirely of letters but some or all are upper case. Your string is not comprised entirely of letters. Your program may NOT:...
Using Python Write a program that does the following in order: 1.     Asks the user to enter...
Using Python Write a program that does the following in order: 1.     Asks the user to enter a name 2.     Asks the user to enter a number “gross income” 3.     Asks the user to enter a number “state tax rate” 4.     Calculates the “Federal Tax”, “FICA tax” and “State tax” 5.     Calculates the “estimated tax” and round the value to 2 decimal places 6.     Prints values for “name”, “gross income” and “estimated tax” The program should contain three additional variables to store the Federal tax, FICA...
Using Python write a program that does the following in order: 1. Ask user to enter...
Using Python write a program that does the following in order: 1. Ask user to enter a name 2. Ask the user to enter five numbers “amount1”, “amount2”, “amount3”, “amount4”, “amount5” 3. Calculate the sum of the numbers “amount1”, “amount2”, “amount3”, “amount4”, “amount5” 4. If the sum is greater than 0, print out the sum 5. If the sum is equal to zero, print out “Your account balance is zero” 6. If the sum is less than 0, print out...
Write a Python code that when the temperature of the CPU in the raspberry pi exceeds...
Write a Python code that when the temperature of the CPU in the raspberry pi exceeds 40 degrees Celsius you receive an email.
Prompt: Produce a 4th order Runge Kutta code in PYTHON that evaluates the following second order...
Prompt: Produce a 4th order Runge Kutta code in PYTHON that evaluates the following second order ode with the given initial conditions, (d^2y/dt^2) +4(dy/dt)+2y=0, y(0)=1 and y'(0)=3. After your code can evaluate the 2nd order ode, add a final command to plot your results. You may only use python.
Please write in Python code Write a program that stores the following data in a tuple:...
Please write in Python code Write a program that stores the following data in a tuple: 54,76,32,14,29,12,64,97,50,86,43,12 The program needs to display a menu to the user, with the following 4 options: 1 – Display minimum 2 – Display maximum 3 – Display total 4 – Display average 5 – Quit Make your program loop back to this menu until the user chooses option 5. Write code for all 4 other menu choices
Using python as the coding language please write the code for the following problem. Write a...
Using python as the coding language please write the code for the following problem. Write a function called provenance that takes two string arguments and returns another string depending on the values of the arguments according to the table below. This function is based on the geologic practice of determining the distance of a sedimentary rock from the source of its component grains by grain size and smoothness. First Argument Value Second Argument Value Return Value "coarse" "rounded" "intermediate" "coarse"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT