Question

In: Computer Science

We were asked this: Write a function that takes a list, and returns a list representing...

We were asked this:

Write a function that takes a list, and returns a list representing each word whose reverse is also in the list.

    def find_reversals(lst: List[str]) -> List[str]:

Each pair, such as 'abut', 'tuba', should be represented by the first element encountered. Don't report the same pairs twice.

Don't list palindromes.

I wrote this, which might not be optimal but passes the unit test!

def find_reversals(lst):
#Place to save to
found_reversals=[]
  
#Make each string lowercase
for i in range(len(lst)):
lst[i]=lst[i].lower()
  
#Check the lowercase list
for i in range(len(lst)):
for j in range(i+1,len(lst)):
#Reverse the string using indexing feature ::-1
reversed_string=lst[j][::-1]
#If the original word on the list == the reversed STRING and is not a palindrome
if(lst[i]==reversed_string and lst[i]!=lst[j]):
#If the string is not a duplicate item
if lst[i] not in found_reversals:
#See if a pair exists, then doesn't append in the list
if lst[i][::-1] not in found_reversals:
found_reversals.append(lst[i])
return found_reversals

The next problem wants us to recycle this...

Write a program that finds the reversals in Downey's word list.

List each pair only once, and only report the first word: List 'abut', but not 'tuba'

Do not list palindromes.

    def find_reversals_in_file(fileName: str) -> List[str]:

If you try to open a file that does not exist, you should catch a FileNotFoundError and print an error message in your own words¶

I have this written:

def find_reversals_in_file(filename):
try:
with open(filename) as f:
  
#Use splitlines to remove the \n from the end of lines
f = f.read().splitlines()
  
#Place to save all words from file to
file_words = []
  
#Split the lines of words into multiple words using ' ' as a delimiter
for x in f:
y = x.split()
for temp in y:
#Don't save any spaces
if len(temp.strip()) == 0:
continue
file_words.append(temp)
#If you can't open the file, return an error message.
except:
print("File does not exist.")
return [];
  
lst = find_reversals_in_file("words.txt")
result = find_reversals(lst)
print(f"There were {len(lst)} reversals")

for word in result:
print(word)

What am I missing here? Thank you in advance!

Solutions

Expert Solution

Hi! :)

Here's the working code to solve the assignment:

def find_reversals(lst):
    #Place to save to
    found_reversals=[]
  
    #Make each string lowercase
    for i in range(len(lst)):
        lst[i]=lst[i].lower()
  
    #Check the lowercase list
    for i in range(len(lst)):
        for j in range(i+1,len(lst)):
            #Reverse the string using indexing feature ::-1
            reversed_string=lst[j][::-1]
            #If the original word on the list == the reversed STRING and is not a palindrome
            if(lst[i]==reversed_string and lst[i]!=lst[j]):
                #If the string is not a duplicate item
                if lst[i] not in found_reversals:
                    #See if a pair exists, then doesn't append in the list
                    if lst[i][::-1] not in found_reversals:
                        found_reversals.append(lst[i])
    return found_reversals

'''
The next problem wants us to recycle this...

Write a program that finds the reversals in Downey's word list.

List each pair only once, and only report the first word: List 'abut', but not 'tuba'

Do not list palindromes.

    def find_reversals_in_file(fileName: str) -> List[str]:

If you try to open a file that does not exist, you should catch a FileNotFoundError and print an error message in your own words¶

I have this written:
'''

def find_reversals_in_file(filename):
    try:
        with open(filename) as f:
          
            #Use splitlines to remove the \n from the end of lines
            f = f.read().splitlines()
              
            #Place to save all words from file to
            file_words = []
              
            #Split the lines of words into multiple words using ' ' as a delimiter
            for x in f:
                y = x.split()
                for temp in y:
                    #Don't save any spaces
                    if len(temp.strip()) == 0:
                        continue
                    file_words.append(temp)
            return file_words                                                           # ADDED     - file_words must be returned
    #If you can't open the file, return an error message.
    except:
        print("File does not exist.")
    return [];
  
lst = find_reversals_in_file("words.txt")
result = find_reversals(lst)
# print(f"There were {len(lst)} reversals")                                             # REMOVED   - result is the list of reversals
print(f"There were {len(result)} reversals")                                            # ADDED     - result is the list of reversals

for word in result:
    print(word)

As you can see, I tried adding indentations to the code myself because the community software has mangled up the whitespace in your code. I have added comments with proper reason to the edits.

Here's a demo run:

Hope this helps! :)


Related Solutions

Write a function called draw_card. It takes no arguments and returns an integer representing the value...
Write a function called draw_card. It takes no arguments and returns an integer representing the value of a blackjack card drawn from a deck. Get a random integer in the range 1 to 13, inclusive. If the integer is a 1, print "Ace is drawn" and return 1. If the integer is between 2 and 10, call it x, print "<x> is drawn" and return x (print the number, not the string literal "<x>"). If the number is 11, 12,...
Write a Python function that takes a list of integers as a parameter and returns the...
Write a Python function that takes a list of integers as a parameter and returns the sum of the elements in the list. Thank you.
Write a Python function that takes a list of integers as a parameter and returns the...
Write a Python function that takes a list of integers as a parameter and returns the sum of the elements in the list. Thank you.
USING PYTHON, write a function that takes a list of integers as input and returns a...
USING PYTHON, write a function that takes a list of integers as input and returns a list with only the even numbers in descending order (Largest to smallest) Example: Input list: [1,6,3,8,2,5] List returned: [8, 6, 2]. DO NOT use any special or built in functions like append, reverse etc.
Use Scheme Language Write a Scheme function that takes a list and returns a list identical...
Use Scheme Language Write a Scheme function that takes a list and returns a list identical to the parameter except the third element has been deleted. For example, (deleteitem '(a b c d e)) returns ‘(a b d e) ; (deleteitem '(a b (c d) e)) returns ‘(a b e).
SML Complete the following programs. 1. Write a function listify that takes a list and returns...
SML Complete the following programs. 1. Write a function listify that takes a list and returns a list of lists where each element of first list becoming its own single-element list (Fill in the code here) fun main() = let val lst = (explode "rad"); in print (PolyML.makestring ( listify lst )) end; 2. Write a function splitlist that takes a list of pairs and returns a pair of lists that has the firsts of the pairs in one list...
Write a function that takes a number as input, and returns the character A if the...
Write a function that takes a number as input, and returns the character A if the input is 90 and above, B if it’s 80 and above but less than 90, C if it’s at least 70 but less than 80, D if it’s at least 60 but less than 70, and F if it’s less than 60. If the input is not a number or is negative, the function should exit 1 with an error (by calling the Matlab...
write a function that takes as input the root of a general tree and returns a...
write a function that takes as input the root of a general tree and returns a binary tree generated by the conversion process illustrated in java
PYTHON: Write a function insertInOrder that takes in a list and a number. This function should...
PYTHON: Write a function insertInOrder that takes in a list and a number. This function should assume that the list is already in ascending order. The function should insert the number into the correct position of the list so that the list stays in ascending order. It should modify the list, not build a new list. It does not need to return the list, because it is modifying it.   Hint: Use a whlie loop and list methods lst = [1,3,5,7]...
Write a Python function that takes a list of string as arguments. When the function is...
Write a Python function that takes a list of string as arguments. When the function is called it should ask the user to make a selection from the options listed in the given list. The it should get input from the user. Place " >" in front of user input. if the user doesn't input one of the given choices, then the program should repeatedly ask the user to pick from the list. Finally, the function should return the word...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT