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

Write a boolean function that is given a binary tree and returns true if and only...
Write a boolean function that is given a binary tree and returns true if and only if the tree has an odd number of nodes. An empty tree is considered to have an even number of nodes. Notes: The function should have just one argument, a pointer to the root. No global variables may be used. No additional functions may be defined. You may not count the number of nodes.
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++
Python: Write a function named calc_odd_sum that accepts a positive integer as the argument and returns...
Python: Write a function named calc_odd_sum that accepts a positive integer as the argument and returns the sum of all the odd numbers that are less than or equal to the input number. The function should return 0 if the number is not positive. For example, if 15 is passed as argument to the function, the function should return the result of 1+3+5+7+9+11+13+15. If -10 is passes, it shall return 0. You shall run the program test the result at...
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 :(...
IN PYTHON Write a function capitalize_last(phrase) that takes in a string phrase consisting of arbitrarily capitalized...
IN PYTHON Write a function capitalize_last(phrase) that takes in a string phrase consisting of arbitrarily capitalized words separated by spaces, and returns a new string consisting of those words but with the only the last letter in each word uppercase. You can assume that the string contains only letters and spaces, no punctuation. Examples: >>> capitalize_last('tEst WiTH rANdoM capITaliZATioN') 'tesT witH randoM capitalizatioN' >>> capitalize_last('') '' >>> capitalize_last('i am the senate') 'I aM thE senatE'
Write a function bracket_by_len that takes a word as an input argument and returns the word...
Write a function bracket_by_len that takes a word as an input argument and returns the word bracketed to indicate its length. Words less than five characters long are bracketed with << >>, words five to ten letters long are bracketed with (* *), and words over ten characters long are bracketed with /+ +/. Your function should require the calling function to provide as the first argument, space for the result, and as the third argument, the amount of space...
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.
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...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT