Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: First In First Out Print

Tags:

python

lifo

I'm a beginner in python and I'm having an issue with this program:

The program below is a Last In First Out (LIFO). I want to make it First in First Out (FIFO) Program.

from NodeList import Node

class QueueLL:

    def __init__(self):
        self.head = None


    def enqueueQLL(self,item):
        temp = Node(str(item))
        temp.setNext(self.head) 
        self.head = temp
        length = max(len(node.data) for node in self.allNodes()) if self.head else 0
        print('\u2510{}\u250c'.format(' '*length))
        for node in self.allNodes():
            print('\u2502{:<{}}\u2502'.format(node.data, length))
        print('\u2514{}\u2518'.format('\u2500'*length))

Here is the NodeList:

class Node:

    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

NOTE: The "Rainbow" should be at the bottom of "Arc" or in FIFO (pic below is LIFO)

I'm thinking to put a new def like setPrevious in the NodeList But I dont know how. (to be honest I'm really new on these self.head = none stuffs . I used to write self.items = [])

Any help and tips will be appreciated! Thank you!

like image 215
arcwinolivirus Avatar asked Oct 07 '13 08:10

arcwinolivirus


1 Answers

Apart from learning purposes I would not advise using a custom data structure for making a LIFO or FIFO. The built in data-type list is just fine after all.

You can add items using the append method and remove them using pop. For a LIFO this would look like this:

stack = list()
stack.append(1)
stack.append(2)
stack.append(3)

print stack.pop()  #3
print stack.pop()  #2
print stack.pop()  #1

If you supply an integer argument for pop you can specify which element to remove. For a FIFO use the index 0 for the first element:

stack = list()
stack.append(1)
stack.append(2)
stack.append(3)

print stack.pop(0)  #1
print stack.pop(0)  #2
print stack.pop(0)  #3
like image 129
Constantinius Avatar answered Nov 01 '22 07:11

Constantinius