I can't print each element in a queue - python

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

Related

Check whether a given string is palindrome using Deque

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]

how to print <__main__.LinkedList object at 0x01BA8A90>? [duplicate]

This question already has answers here:
How to print instances of a class using print()?
(12 answers)
Closed 3 years ago.
can anybody explain why it is showing me and how to print it?
what am I doing wrong and how to print this object reference?
i have also tried printing new_list(inside sort() ) but still the same
I am printing list then why it is not showing
I know some of the people asked before about related to this...but still I didn't get it.
class node(object):
def __init__(self, d, n=None):
self.data=d
self.next_node=n
def get_data(self):
return self.data
def set_data(self,d):
self.data=d
def get_next(self):
return self.next_node
def set_next(self, n):
self.next_node=n
def has_next(self):
if self.get_next() is not None:
return True
else:
False
class LinkedList(object):
def __init__(self, r=None):
self.root=r
self.size=0
def get_size(self):
return self.size
def add(self,d):
new_node = node(d, self.root)
self.root = new_node
self.size+=1
def sort(self):
if self.size>2:
newlist = []
this_node = self.root
newlist.append(this_node)
while this_node.has_next():
this_node = this_node.get_next()
newlist.append(this_node)
newlist = sorted(newlist ,key = lambda node: node.data,reverse=True)
newLinkedList = LinkedList()
for element in newlist:
newLinkedList.add(element)
return newLinkedList
return self
new_list=LinkedList()
new_list.add(10)
new_list.add(20)
new_list.add(30)
new_list.sort()
i expected that it will print list print a list
but it is showing <main.LinkedList object at 0x00E20BB0>
how to print this object ?
You are not printing out node values of the linked list instead you are printing out the return value of the sort() function which is an object of the class LinkedList.
If you want to print the linked list, you have to traverse the list and print out each node value individually.
Here is the recursive solution of how you can print a linked list.
def print_list(head):
if head != null:
print(head.val)
print_list(head.next)
You can call this method after calling the sort function

Python sort with last added element in the queue

Actually my sort algorithm works, but there is a problem.
I have a class namely SortedItem which includes
def __init__(self, point, cost):
self.coordinate = point
self.cost = cost
and I have also priority queue which sorts the this SortedItem by its cost:
class PriorityQueue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def sortComparatorByCost(self, item):
return item.cost
def enqueue(self, item):
self.items.append(item)
self.items.sort(key=self.sortComparatorByCost, reverse=True)
def dequeue(self):
return self.items.pop()
def returnQueueAsString(self):
queue_str = ""
for eachItem in self.items:
queue_str += str(eachItem) + " "
return queue_str
def isQueueContainsElement(self, element):
for eachElement in self.items:
if eachElement[0] == element:
return True
return False
The problem occurs here:
- I have defined some order to add queue. Let's say I am adding this objects to the queue:
obj1 = SortedItem((1,0), 10))
queue.enqueue(obj1)
obj2 = SortedItem((2,0), 15))
queue.enqueue(obj2)
obj3 = SortedItem((2,1), 15))
queue.enqueue(obj3)
Now I have to get objects from queue in this order (obj1, obj2, obj3).
However python built-in sort function sort these objects like this: (obj1, obj3, obj2) (because obj2 and obj3 has the same cost)
How can i solve this issue. I mean If 2 objects cost is the same, I should get the first added one.
Note that: I have just created a simple example of my problem. If you try this code you may get the objects in this order: obj1, obj2, obj3
Instead of sorting the items in reverse order and removing them from the right,
def enqueue(self, item):
self.items.append(item)
self.items.sort(key=self.sortComparatorByCost, reverse=True)
def dequeue(self):
return self.items.pop()
you could remove them from the left. That would avoid reversing the order of insertion of the items with the same cost.
def enqueue(self, item):
self.items.append(item)
self.items.sort(key=self.sortComparatorByCost)
def dequeue(self):
return self.items.pop(0)
Removing items from the beginning of a list is not efficient, however, so you could better use a deque (replacing pop(0) by popleft()) to fix that. A deque on the other hand, has no in-place sort() method, so would need to replace self.items.sort() by self.items = deque(sorted(self.items)) as well.

Implementing a queue in Python - two isempty() methods giving different answers

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.

Stacks iteration python3

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

Categories