Question

python problem: ( use a loop to read each character from the string and insert into...

python problem: ( use a loop to read each character from the string and insert into the stack)

1. The function main a5.py continually asks the user for a string, and calls isPalindrome to check whether each string is a palindrome.

A palindrome is a word or sequence that reads the same backward as forward, e.g., noon, madam or nurses run.

2. Your function must ignore spaces: when the user enters 'nurses run', the function returns True, to indicate that it is a palindrome.

3. In your code (in isPalindrome) you must use a stack to determine whether the input strings are palindromes. The program imports the Stack class defined stack.py. Save both files (stack.py and a5.py) in the same directory, then modify and test a5.py.

"""

File: a5.py

"""
from stack import Stack

def isPalindrome(sentence):
"""Returns True if sentence is a palindrome
or False otherwise."""
stk = Stack() # Creates a stack called stk.

# *** Write your code here ***
  
return True

# *** Do not modify main() ***
def main():
while True:
sentence = input("Enter some text or just hit Enter to quit: ")
if sentence == "":
break
elif isPalindrome(sentence):
print("It's a palindrome.")
else:
print("It's not a palindrome.")

main()

"""
File: stack.py

"""

class Stack:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def push(self, item):
self.items.append(item)

def pop(self):
return self.items.pop()

def peek(self):
return self.items[len(self.items)-1]

def size(self):
return len(self.items)

Homework Answers

Answer #1

I have used 2 stacks to check for the palindrome, Stack.py is same as it is, and the method ignores the white spaces , or if you want to also ignore puntuations or any ther letter then just put the character into the black_list [] array.

from stack import Stack

def isPalindrome(sentence):

stk1 = Stack()
stk2 = Stack()

if not sentence:
         return false
     black_list = [" "]
     for c in black_list:
         sentence = "".join(sentence.split(c))
     sentence = sentence.lower()

for ch in sentence:
    stk1.push(ch)

for letters in sentence:
  
       stk2.push(letters)
       stk2.reverse()

if stack_equals(stk1,stk2);
return True

def stack_equals(stk1, stk2):
   while True:
       try:
           if stk1.pop() != stk2.pop():
               return False
       except IndexError:
           return True


# *** Do not modify main() ***
def main():
while True:
sentence = input("Enter some text or just hit Enter to quit: ")
if sentence == "":
break
elif isPalindrome(sentence):
print("It's a palindrome.")
else:
print("It's not a palindrome.")

main()

Know the answer?
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
Similar Questions
Python Programming Build a python programming that asks the user for a three-letter substring. The program...
Python Programming Build a python programming that asks the user for a three-letter substring. The program should then proceed to read the file strings.txt. Each line in strings.txt will contain a string. Your program should then test to see how many non-overlapping occurrences of the three-letter substring occur in that string and test whether the string is a palindrome. The program should then proceed to create an output file string_stats.txt, which contains the original data on one line and the...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21,...
Python Blackjack Game Here are some special cases to consider. If the Dealer goes over 21, all players who are still standing win. But the players that are not standing have already lost. If the Dealer does not go over 21 but stands on say 19 points then all players having points greater than 19 win. All players having points less than 19 lose. All players having points equal to 19 tie. The program should stop asking to hit if...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):         self.name = name         self.pop = pop         self.area = area         self.continent = continent     def getName(self):         return self.name     def getPopulation(self):         return self.pop     def getArea(self):         return self.area     def getContinent(self):         return self.continent     def setPopulation(self, pop):         self.pop = pop     def setArea(self, area):         self.area = area     def setContinent(self, continent):         self.continent = continent     def __repr__(self):         return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ') TASK 2 Python Program: File: catalogue.py from Country...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters...
convert this code to accept int value instead of float values using python. Make sure to...
convert this code to accept int value instead of float values using python. Make sure to follow the same code. do not change the steps and make sure to point to what code you replaced. make sure to have 2 files Method:----------------------- #define a python user difined method def get_float_val (prompt): is_num = False str_val = input (prompt) #prming read for our while #while is_num == False: (ignore this but it works) old school while not is_num: try: value =...
write a code in python Write the following functions below based on their comments. Note Pass...
write a code in python Write the following functions below based on their comments. Note Pass is a key word you can use to have a function the does not do anything. You are only allowed to use what was discussed in the lectures, labs and assignments, and there is no need to import any libraries. #!/usr/bin/python3 #(1 Mark) This function will take in a string of digits and check to see if all the digits in the string are...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4...
please use linux/unix command terminal to complete, step 1 1-create a new directory named by inlab4 enter directory inlab4 create a new file named by reverse.c with the following contents and then close the file: /*reverse.c */ #include <stdio.h> reverse(char *before, char *after); main() { char str[100]; /*Buffer to hold reversed string */ reverse("cat", str); /*Reverse the string "cat" */ printf("reverse(\"cat\")=%s\n", str); /*Display result */ reverse("noon", str); /*Reverse the string "noon" */ printf("reverse(\"noon\")=%s\n", str); /*Display result */ } reverse(char *before,...
In this assignment, you’ll make an inventory system for a store’s items, including produce and books....
In this assignment, you’ll make an inventory system for a store’s items, including produce and books. The starter program is an inventory system for only produce. 1. Include the price of an item by adding to the Item class the protected data member int priceInDollars that stores the price in dollars of an individual item. Write a public function SetPrice with a single int parameter prcInDllrs and returns nothing. SetPrice assigns the value of prcInDllrs to priceInDollars. Modify the AddItemToInventory...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these...
**[70 pts]** You will be writing a (rather primitive) online store simulator. It will have these classes: Product, Customer, and Store. All data members of each class should be marked as **private** (a leading underscore in the name). Since they're private, if you need to access them from outside the class, you should do so via get or set methods. Any get or set methods should be named per the usual convention ("get_" or "set_" followed by the name of...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT