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)
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()
Get Answers For Free
Most questions answered within 1 hours.