Question

3. Did you ever wonder what are the longest words that when spelled backwards form other...

3. Did you ever wonder what are the longest words that when spelled backwards form other valid words? Well, now you get to answer that question (even if you never asked it ;-)). Write a function writeLongestBackwardsWordsToFile(M) that writes a file ‘topMBackwardsWords.txt’ (e.g. ‘top3BackwardsWords.txt’ if M = 3), containing the M longest words and their corresponding backwards word together on one line, and different word pairs on different lines. Try not to duplicate the same word pair (with order reversed) on a different line, but if you cannot solve the problem without doing this no points will be deducted. See the following expected output for ‘top3BackwardsWords.txt’:

Hint: Break the function into 3 sections: 1) read in wordlist.txt and convert to a set, 2) for-loop through the set of words and check if the reverse word is also in the set (sets are very fast at checking membership, lists are slowww…), forming a list of reversible words. 3) Sort the list of words by length (make a list of tuples) and write first M to file.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

# python code

def writeLongestBackwardsWordsToFile(M):
    # read in wordlist.txt and convert to a set
    readWords = open('wordlist.txt')
    wordSet = set(readWords.read().split())
    readWords.close()
    wordList = []
    outFIle = "top%dBackwardsWords.txt" % (M)

    # for-loop through the set of words and check if the reverse word is also in the set
    for i in wordSet.copy():
        if i[::-1] in wordSet:
            wordList.append(i)
            wordSet.remove(i)
    # Sort the list of words by length
    wordList.sort(key=len, reverse=True)

    # write first M to file.
    file = open(outFIle, "w")
    for x in range(0, M):
        file.write(wordList[x])
        file.write("\t")
        file.write(wordList[x][::-1])
        file.write("\n")
    file.close()

writeLongestBackwardsWordsToFile(3)


'''
top3BackwardsWords.txt

redrawer    rewarder
halalah halalah
reifier reifier

'''

Add a comment
Answer #2

# python code

def writeLongestBackwardsWordsToFile(M):
    # read in wordlist.txt and convert to a set
    readWords = open('wordlist.txt')
    wordSet = set(readWords.read().split())
    readWords.close()
    wordList = []
    outFIle = "top%dBackwardsWords.txt" % (M)

    # for-loop through the set of words and check if the reverse word is also in the set
    for i in wordSet.copy():
        if i[::-1] in wordSet:
            wordList.append(i)
            wordSet.remove(i)
    # Sort the list of words by length
    wordList.sort(key=len, reverse=True)

    # write first M to file.
    file = open(outFIle, "w")
    for x in range(0, M):
        file.write(wordList[x])
        file.write("\t")
        file.write(wordList[x][::-1])
        file.write("\n")
    file.close()

writeLongestBackwardsWordsToFile(3)


'''
top3BackwardsWords.txt

redrawer    rewarder
halalah halalah
reifier reifier

'''

Add a comment
Answer #3

# python code

def writeLongestBackwardsWordsToFile(M):
    # read in wordlist.txt and convert to a set
    readWords = open('wordlist.txt')
    wordSet = set(readWords.read().split())
    readWords.close()
    wordList = []
    outFIle = "top%dBackwardsWords.txt" % (M)

    # for-loop through the set of words and check if the reverse word is also in the set
    for i in wordSet.copy():
        if i[::-1] in wordSet:
            wordList.append(i)
            wordSet.remove(i)
    # Sort the list of words by length
    wordList.sort(key=len, reverse=True)

    # write first M to file.
    file = open(outFIle, "w")
    for x in range(0, M):
        file.write(wordList[x])
        file.write("\t")
        file.write(wordList[x][::-1])
        file.write("\n")
    file.close()

writeLongestBackwardsWordsToFile(3)


'''
top3BackwardsWords.txt

redrawer    rewarder
halalah halalah
reifier reifier

'''

Add a comment
Know the answer?
Add Answer to:
3. Did you ever wonder what are the longest words that when spelled backwards form other...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

  • Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that...

    Overview: file you have to complete is WordTree.h, WordTree.cpp, main.cpp Write a program in C++ that reads an input text file and counts the occurrence of individual words in the file. You will see a binary tree to keep track of words and their counts. Project description: The program should open and read an input file (named input.txt) in turn, and build a binary search tree of the words and their counts. The words will be stored in alphabetical order...

  • To insure that file output is written to the disk you need to execute what method?...

    To insure that file output is written to the disk you need to execute what method? a. commit() b. write() c. close() d. complete() The following is called the ________ of a function. def myFunction(x,y) : a. header b. footer c. sentinel d. index True or False: A commonly used program that uses regular expressions is grep. True or False: In Python exception handling provides a mechanism for passing control from the point of the error detection to a handler...

  • . . In this programming assignment, you need to write a CH+ program that serves as...

    . . In this programming assignment, you need to write a CH+ program that serves as a very basic word processor. The program should read lines from a file, perform some transformations, and generate formatted output on the screen. For this assignment, use the following definitions: A "word" is a sequence of non-whitespace characters. An "empty line" is a line with no characters in it at all. A "blank line" is a line containing only one or more whitespace characters....

  • CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the fil...

    CSC110 Lab 6 (ALL CODING IN JAVA) Problem: A text file contains a paragraph. You are to read the contents of the file, store the UNIQUEwords and count the occurrences of each unique word. When the file is completely read, write the words and the number of occurrences to a text file. The output should be the words in ALPHABETICAL order along with the number of times they occur and the number of syllables. Then write the following statistics to...

  • In problem 3, you will write a function, findvertically (), which will determine whether or not...

    In problem 3, you will write a function, findvertically (), which will determine whether or not a given word exists in a word search puzzle vertically. In word search puzzles, words can be written upwards or downwards. For example, "BEAK" appears at [1] [3] written downwards, while "BET" appears at [2] [2] written upwards: [["C", "A", "T", "X", "R"], ["D", "T", "E", "B", "L"], ["A" "R" "B", "E", "Z"], ["X", "O", "E", "A", "U"], ["J", "S", "O", "K", "W"]] Your...

  • Implement the histogram function to complete the desired program. You must use dynamically allocated arrays for...

    Implement the histogram function to complete the desired program. You must use dynamically allocated arrays for this purpose. For your initial implementation, use ordered insertion to keep the words in order and ordered sequential search when looking for words. Note that the array utility functions from the lecture notes are available to you as art of the provided code. Although we are counting words in this program, the general pattern of counting occurrences of things is a common analysis step...

  • Write a c++ program in that file to perform a “Search and Replace All” operation. This...

    Write a c++ program in that file to perform a “Search and Replace All” operation. This operation consists of performing a case-sensitive search for all occurrences of an arbitrary sequence of characters within a file and substituting another arbitrary sequence in place of them. Please note: One of the biggest problems some students have with this exercise occurs simply because they don’t read the command line information in the course document titled “Using the Compiler’s IDE”. Your program: 1. must...

  • Have you ever wanted to predict the future? Well the Magic Eight Ball does just that....

    Have you ever wanted to predict the future? Well the Magic Eight Ball does just that. The original game was a softball sized “8-ball”. You would ask a question, shake it up and look at the result. There are 20 responses…10 positive, 5 negative, and 5 are vague. For this project, we want to recreate this, but give the ability to read in a set of responses, and add additional responses, and print out all of the responses in alphabetical...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT