repl.it
@big_deelan/

Palindrome stack

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# My Stack class - attributes are maxsize, current size, top
# methods are push, pop, isEmpty and isFull and Display

class Stack:

  # The constructor sets up all of my object data (attributes)
  # It takes one parameter - maxsize which defines the maximum size of the Stack
  def __init__(self, maxsize):
    self.maxsize = maxsize
    self.list = []
    for i in range(self.maxsize):
      self.list.append("")
    self.currentsize = 0
    self.top = -1

  # a function to return True if the stack is at full capacity and False otherwise - it uses the shortcut technique....
  def isFull(self):
    return self.currentsize == self.maxsize

  # a function to return True if the stack is currently empty and False otherwise
  def isEmpty(self):
    return self.currentsize == 0

  # Our push function adds elements to the stack
  def push(self, item):
    if self.isFull():
      print("Error, your stack is already full")
    else:
      # Move the top pointer forwards
      self.top += 1
      #add the new item to the list at the new top position
      self.list[self.top] = item
      #increase the size
      self.currentsize += 1
      print("You have successfully added", item, "to the stack")

  # Our pop function removes elements from the stack
  def pop(self):
    if self.isEmpty():
      print("Error, your stack is already empty")
    else:
      # Get the item off the stack
      item = self.list[self.top]
      # Blank it out
      self.list[self.top] = ""
      # move the pointer down one position
      self.top -= 1
      # reduce the size 
      self.currentsize -= 1
      print("You have successfully removed", item, "from the stack")
      #return the item
      return item
  
  def display(self):
    # We need to show the stack in a stack type way
    print(self.list)

# Class definition Over
myString = input("Please enter a word or phrase to be tested: ")
print("")
list1 = list(myString) # convert myString to a list of characters
list2 = []
palindrome = False
numChars = len(list1)
s = Stack(10) # Defines the size of the stack
for i in range(numChars):
  s.push(list1[i])
for i in range (numChars):
  list2 += s.pop()
if list1 == list2:
  palindrome = True
  print("\nThis is a palindrome.")
else:
  print("\nThis is not a palindrome.")
s.display()
Fetching token
?