I have written a python code to check whether a given string is a palindrome. However, there is something wrong with the code. For every string it returns True, i.e. it's a palindrome.
What is wrong with my code?
This is my code:
class Deque:
def __init__(self):
self.items=[]
def empty(self):
return self.items==[]
def push_back(self,item):
self.items.append(item)
def push_front(self,item):
self.items.insert(0,item)
def pop_back(self):
self.items.pop()
def pop_front(self):
self.items.pop(0)
def back(self):
return self.items[-1]
def front(self):
return self.items[0]
def size(self):
return len(self.items)
def at(self,index):
return self.items[index]
def palcheck(string):
D=Deque()
for char in string:
D.push_back(char)
stillEqual=True
while D.size() >1 and stillEqual:
first=D.pop_front()
last=D.pop_back()
if first!=last:
stillEqual=False
return stillEqual
print(palcheck("lsknfjbdf"))
Your pop methods don't explicitly return anything - and therefore they implicitly return None.
As a result, if first!=last: will always do if None!=None:.
Simply change your pop methods to return the popped value:
def pop_back(self):
return self.items.pop()
def pop_front(self):
return self.items.pop(0)
To test if a string is a palindrome it's as simple as:
def ispalindrome(s):
return s == s[::-1]
Related
I have stack code:
class Stack:
def __init__(self):
self.__data = []
def empty(self):
return len(self.__data) == 0
def size(self):
return len(self.__data)
def push(self, x):
self.__data.append(x)
def pop(self):
return self.__data.pop()
and adds numbers 1, 2:
stack = Stack()
stack.push(1)
stack.push(2)
and I don't know how to print __data list?
so that it shows 1,2 in the list?
[1,2]
As __data is a private attribute of stack object, it cannot be accessed outside the class. Instead define an instance method to print the stack list as shown below.
class Stack:
def print_stack(self):
print(self.__data)
Now if you call print_stack() on an instance. It will print the __data list.
You can use __str__ method to print the values using print() or __repr__ for direct representation.
class Stack:
def __init__(self):
self.data = []
def empty(self):
return len(self.data) == 0
def size(self):
return len(self.data)
def push(self, x):
self.data.append(x)
def pop(self):
return self.data.pop()
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self.data)
>>> stack = Stack()
>>> stack.push(1)
>>> stack.push(2)
>>> print(stack) ## using __str__
# [1, 2]
>>> stack ## using __repr__
# [1, 2]
I have one more question. My code:
class Stack:
def __init__(self):
self.data = []
def empty(self):
return len(self.data) == 0
def size(self):
return len(self.data)
def push(self, x):
self.data.append(x)
def pop(self):
if len(self.data) == 0:
print("underflow")
else:
return self.data.pop()
def __str__(self):
return str(self.data)
stack = Stack()
stack.push(1)
stack.push(2)
print(stack)
I print the list as I wanted:
[1,2]
Now i wonder if i can work on this list? That is, as always on the lists:
In this case:
list = stack
list[0]
1
Can you recommend some simple courses where do Class is explained? I feel confused and my questions seem simple...
I'm doing some basic Python programming practice exercises and tried to implement a queue (using lists). Unfortunately, I'm getting behavior for my isempty() function that I don't understand. When running the code below, the last two lines give different answers: A yields False, while B yields True. Why doesn't A also yield False?
class Queue:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
return self.size == 0
q = Queue()
q.push("a")
q.push("b")
print(q.pop())
print(q.isempty())
print(q.pop())
print(q.isempty()) # shouldn't this (A)...
print(q.size()==0) # ...and this (B) yield the same answer?
Just change your isempty() method to:
def isempty(self):
return self.size() == 0
Your implementation of Queue.isempty() is checking to see if the method size is equal to the integer 0, which will never be true.
class Queue:
def __init__(self):
self.items = []
def push(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def size(self):
return len(self.items)
def isempty(self):
return self.size == 0
q = Queue()
print(q.size)
Produces:
<bound method Queue.size of <__main__.Queue object at 0x02F4EA10>>
The easiest solution is to use Christopher Shroba's suggestion to modify your Queue.isempty() implementation to use the list's size method.
I'm a complete beginner for programming. I created the class "queue",added some elements to it and tried to print each element of the queue as following but I couldn't. Please help me!
Thanks in advance!
edited for formatting
class queue:
def __init__(self):
self.items = []
def isempty(self):
return self.items == []
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[len(self.items)-1]
q=queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
for n in q():
print "This time, it's: "+ str(n)
When you create your own class implementation then you you have to define each and every behaviour of that class, the for loop is only applicable to iterables and to make your object iterable you need to define __iter__ method inside your class which would be called implicitly whenever you try to iterate over your object.
class queue:
def __init__(self):
self.items = []
def isempty(self):
return self.items == []
def enqueue(self,item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[len(self.items)-1]
def __iter__(self):
for i in self.items:
yield i
q=queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
for n in q:
print "This time, it's: "+ str(n)
You are iterating through a non-sequence type:
for n in q():
print "This time, it's: "+ str(n)
This is the correct way:
for n in q.items:
print "This time, it's: "+ str(n)
You either need to define an __iter__ method to make your queue iterable, or you need to modify the loop to use your defined methods.
Here q is an instance of class queue. Also q is not callable.And items is the instance variable.So you have to use
for n in q.items:
print "This time, it's: "+ str(n)
Defining the __getitem__ magic method is possibly the simplest way to make your queue iterable.
class queue:
def __init__(self):
self.items = []
def isempty(self):
return self.items == []
def enqueue(self,item):
self.items.insert(0, item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def peek(self):
return self.items[len(self.items)-1]
def __getitem__(self, i):
return self.items[i]
q=queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
for n in q:
print "This time, it's: "+ str(n)
Also don't use for n in q():. Thats going to try and call your queue object as a function. As q is not a function, it fails.
As a consequence of implementing __getitem__, you are also able to reference the elements in your queue by index directly on the queue object.
e.g.
print q[0]
prints
3
Well you have to enqueue something in the queue to print it out!
this code after your class
q=queue()
q.enqueue(3)
q.enqueue(4)
q.enqueue(55)
for n in q():
print "This time, it's: "+ str(n)
You never put anything in the queue. So it is empty. Therefore nothing gets printed. Try adding some objects (call the function q.enqueue) and then perhaps they will print.
In my case when import Queue the answer selected above doesn't work.
What really works is that:
for i in q.queue:
print i
I'm working on a homework assignment where I shall implement selection sorting using forward iterators for both python lists and linked lists(single).
Here are some codes I have for iterators:
from abc import *
class ForwardIterator(metaclass=ABCMeta):
#abstractmethod
def getNext(self):
return
#abstractmethod
def getItem(self):
return
#abstractmethod
def getLoc(self):
return
#abstractmethod
def clone(self):
return
def __eq__(self, other):
return self.getLoc() == other.getLoc()
def __ne__(self, other):
return not (self == other)
def __next__(self):
if self.getLoc() == None:
raise StopIteration
else:
item = self.getItem()
self.getNext()
return item
class ForwardAssignableIterator(ForwardIterator):
#abstractmethod
def setItem(self, item):
"""Sets the item at the current position."""
return
class PythonListFAIterator(ForwardAssignableIterator):
def __init__(self, lst, startIndex):
self.lst = lst
self.curIndex = startIndex
def getNext(self):
self.curIndex += 1
def getItem(self):
if self.curIndex < len(self.lst):
return self.lst[self.curIndex]
else:
return None
def setItem(self, item):
if self.curIndex < len(self.lst):
self.lst[self.curIndex] = item
def getLoc(self):
if self.curIndex < len(self.lst):
return self.curIndex
else:
return None
def clone(self):
return PythonListFAIterator(self.lst, self.curIndex)
The LinkedListFAIterator is similar to PythonListFAIterator, plus getStartIterator, and __iter__ method.
I don't know how I can write codes to implement selection sort with one paraemter, a FAIterator (the forward iterator). Please help me. I know I shall find the minimum element and put it at the beginning of the list. I also know that I shall use the clone method to create multiple iterators to keep track of multiple locations at once. But I don't know how to write the code.
Please give me some hints.
Ok so im trying to input a word in a stack and I want to print all of them after I input a string. So I can only print them one at a time. I tried using a for loop outside but Stacks are apparently not iterable. So I iterating it inside the stack. It still is not working.
class Stack:
def __init__(self):
self.items = []
def push(self,items):
self.items.insert(0,items)
def pop(self):
for x in self.items:
print( self.items.pop(0))
def show(self):
print (self.items)
s = Stack()
s.show()
placed = input("enter")
item = s.pop()
print(item, "is on top", s)
Give your Stack class a __len__ method, this will make testing if the stack is empty easier:
class Stack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def show(self):
print (self.items)
def __len__(self):
return len(self.items)
stack = Stack()
stack.push('World!')
stack.push('Hello')
while stack: # tests the length through __len__
print(stack.pop())
Note that I simply .append() to the end of the .items list, then later on .pop() (no arguments) again, removing from the end of the list.
To make your class an iterable type, you'd need to add at least an __iter__ method, optionally together with a .__next__() method:
class Stack:
# rest elided
def __iter__(self):
return self
def next(self):
try:
return self.items.pop()
except IndexError: # empty
raise StopIteration # signal iterator is done