Question

In: Computer Science

PYTHON: Write a function named is_palindrome() that returns boolean True if a word or phrase is...

PYTHON:

  1. Write a function named is_palindrome() that returns boolean True if a word or phrase is a palindrome, and boolean False if it is not.
  2. The palindromes for this problem are contained in the list below. You must use this list in your solution.
  3. Use a for loop to retrieve each palindrome and test it.

Your script should test each string in the list of palindromes below. Be aware there's a second list of palindromes embedded in the palindromes list. In other words, palindromes contains strings and it contains a list of strings. Your code should be able to detect whether the item is a list by using the isinstance() function.

Code to get you started

# YOUR COMMENT BLOCK GOES HERE
from random import shuffle

palindromes  = [  "Dennis, Nell, Edna, Leon, Nedra, Anita, Rolf, Nora, Alice, Carol, Leo, Jane, Reed, Dena, Dale, Basil, Rae, Penny, Lana, Dave, Denny, Lena, Ida, Bernadette, Ben, Ray, Lila, Nina, Jo, Ira, Mara, Sara, Mario, Jan, Ina, Lily, Arne, Bette, Dan, Reba, Diane, Lynn, Ed, Eva, Dana, Lynne, Pearl, Isabel, Ada, Ned, Dee, Rena, Joel, Lora, Cecil, Aaron, Flora, Tina, Arden, Noel, and Ellen sinned.", "Depardieu, go razz a rogue I draped.", "Desserts I stressed.", "Detartrated.", "Devo met a Mr., eh, DNA and her mate moved.", "Di as dad said.", "Did I draw Della too tall, Edward? I did?", "Dior droid.", "DNA-land.", "Do geese see god?", "Do good? I? No. Evil anon I deliver. I maim nine more hero-men in Saginaw, sanitary sword a-tuck, Carol, I. Lo! Rack, cut a drowsy rat in Aswan. I gas nine more hero-men in Miami. Reviled, I (Nona) live on. I do, O God.",'"Do nine men interpret?" "Nine men," I nod.', [ "abracadabra!","Mister, mister, on a see-saw with your sister.","Almost every sentence is NOT a palindrome! How unfair!"] ]

# Shuffle the palindromes
shuffle(palindromes)
   
#########
######### YOUR CODE GOES HERE
#########

Solutions

Expert Solution

The entire code is as follows:

def is_palindrome(s):
    s = s.lower()
    
    temp = ''
    for each_letter in s:
        if each_letter.isalpha():
            temp += each_letter    
    s = temp
    
    if s == s[::-1]:
        return True
    return False

from random import shuffle
palindromes  = [  
    "Dennis, Nell, Edna, Leon, Nedra, Anita, Rolf, Nora, Alice, Carol, Leo, Jane, Reed, Dena, Dale, Basil, Rae, Penny, Lana, Dave, Denny, Lena, Ida, Bernadette, Ben, Ray, Lila, Nina, Jo, Ira, Mara, Sara, Mario, Jan, Ina, Lily, Arne, Bette, Dan, Reba, Diane, Lynn, Ed, Eva, Dana, Lynne, Pearl, Isabel, Ada, Ned, Dee, Rena, Joel, Lora, Cecil, Aaron, Flora, Tina, Arden, Noel, and Ellen sinned.", "Depardieu, go razz a rogue I draped.", "Desserts I stressed.", "Detartrated.", "Devo met a Mr., eh, DNA and her mate moved.", "Di as dad said.", "Did I draw Della too tall, Edward? I did?", "Dior droid.", "DNA-land.", "Do geese see god?", "Do good? I? No. Evil anon I deliver. I maim nine more hero-men in Saginaw, sanitary sword a-tuck, Carol, I. Lo! Rack, cut a drowsy rat in Aswan. I gas nine more hero-men in Miami. Reviled, I (Nona) live on. I do, O God.",'"Do nine men interpret?" "Nine men," I nod.', [ "abracadabra!","Mister, mister, on a see-saw with your sister.","Almost every sentence is NOT a palindrome! How unfair!"]
]
shuffle(palindromes)

for each in palindromes:
    if each.__class__ != list().__class__:
        print(each)
        print(is_palindrome(each))
    else:
        for nested_list in each:
            print(nested_list)
            print(is_palindrome(nested_list))

Over here there are two main logics. The nested list logic and is_palindrome logic.

1) is_palidrome()

We pass in the string that we got from the palindrome list. Now first we have to refine the string in order to make it acceptable for our palindrome logic.

We need to remove all the punctuations and spaces from the string. First, we lower case all the letters in the string. Then we remove all the punctuations and spaces by running the first for-loop in the function. This for-loop iterates through the string letter by letter and eliminate anything that is not an alphabet. The palindrome logic isn't that difficult and is shown above in the if condition.

2) nested list workaround

As we are dealing with a nested list, what we can do is set in the condition while iterating through the palindrome list. Over here we check if the element in the palindrome list is a list or a string. If it is not a list we call the is_palindrome function. If it is a list we iterate through that list again and then call the is_palindrome function for the nested list elements.


Related Solutions

In PYTHON: Write a function that receives a sentence and returns the last word of that...
In PYTHON: Write a function that receives a sentence and returns the last word of that sentence. You may assume that there is exactly one space between every two words, and that there are no other spaces at the sentence. To make the problem simpler, you may assume that the sentence contains no hyphens, and you may return the word together with punctuation at its end.
Write function boolean isSorted(int a[], int size). The function returns true if array a is sorted...
Write function boolean isSorted(int a[], int size). The function returns true if array a is sorted in either ascend order or descend order; false otherwise. c++
Write a function checkvertical(board, word, row, col), which returns True if the word word can be...
Write a function checkvertical(board, word, row, col), which returns True if the word word can be added to the board starting at position board[row][col] and going down. The restrictions are (1) it has to fit entirely on the board, (2) it has to intersect and match with one or more non-blank letters on the board, and (3) it cannot change any letters on the board, other than blanks (that is, overlapping mismatches are not allowed). My program isn't working :(...
Declare and define a function named getCurrentHours_OR_Month that accepts one Boolean parameter. If the Boolean parameter...
Declare and define a function named getCurrentHours_OR_Month that accepts one Boolean parameter. If the Boolean parameter is true, the function returns current hours; if the Boolean parameter is false, the function returns current month. o This function will obtain the current system time and extract the hours or the month value from the system time depending on the Boolean being received. o This function will return the extracted value as an integer value. o Note that the system time displays...
Write a GLM function named getInverse that returns the inverse of A. If A does not...
Write a GLM function named getInverse that returns the inverse of A. If A does not have an inverse, the function returns the identify matrix. Assume A is 3x3.
Python: Write a function that receives a one dimensional array of integers and returns a Python...
Python: Write a function that receives a one dimensional array of integers and returns a Python tuple with two values - minimum and maximum values in the input array. You may assume that the input array will contain only integers and will have at least one element. You do not need to check for those conditions. Restrictions: No built-in Python data structures are allowed (lists, dictionaries etc). OK to use a Python tuple to store and return the result. Below...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns:...
Language: Python Function name : sort_by_rating Parameters : file (.csv file), category (string), order (boolean) Returns: None Description : You want to see what order the items of a particular category in your file would be in if you sorted them by rating. Given a file, a category of clothing, and an order boolean (True for ascending order, False for descending order), create a function that writes a file called “sorted_items.csv” that includes all of the items in the specified...
Write a function named "characters" that takes a string as a parameter and returns the number...
Write a function named "characters" that takes a string as a parameter and returns the number of characters in the input string
Write a Python function that returns a list of keys in aDict with the value target....
Write a Python function that returns a list of keys in aDict with the value target. The list of keys you return should be sorted in increasing order. The keys and values in aDict are both integers. (If aDict does not contain the value target, you should return an empty list.) This function takes in a dictionary and an integer and returns a list. def keysWithValue(aDict, target): ''' aDict: a dictionary target: an integer ''' # Your code here
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.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT