Data structures and algorithms implemented by Python: Dual-end queue explanation; python data structures and algorithms

Source: Internet
Author: User

Data structures and algorithms implemented by Python: Dual-end queue explanation; python data structures and algorithms

This article describes the Python-implemented data structure and algorithm dual-end queue. Share it with you for your reference. The specific analysis is as follows:

I. Overview

A double-ended queue (deque) is a linear data structure with queues and stacks. The dual-end queue also has two ends: front and rear. However, unlike the queue, the insert operation can be performed on both ends (first and last, the same is true for delete operations.

Ii. ADT

The dual-end queue ADT (abstract data type) generally provides the following interfaces:

① Deque () creates a dual-end queue
② AddFront (item) inserts an item into the first line
③ AddRear (item) inserts an item to the end of the team
④ RemoveFront () returns the first item and deletes the item from the double-ended queue.
⑤ RemoveRear () returns the item at the end of the team and deletes the item from the dual-end queue.
⑥ Empty () determines whether the dual-end queue is empty
7. size () returns the number of items in the double-ended queue.

The double-end queue operation is as follows:


Iii. Python implementation

In Python, there are two ways to implement the above two-end queue ADT: using the built-in type list, using the standard library collections. deque (actually collections. deque is the standard implementation of double-end queues in Python ).

The two methods differ mainly in performance (For details, refer to collections. deque | TimeComplexity ):

Operation | Implementation list collections.deque
-----------------------------------------
addFront O (n) O (1)
-----------------------------------------
addRear O (1) O (1)
-----------------------------------------
removeFront O (n) O (1)
-----------------------------------------
removeRear O (1) O (1)

1. Use the built-in type list

#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Deque:
  def __init__(self):
    self.items = []
  def addFront(self, item):
    self.items.insert(0, item)
  def addRear(self, item):
    self.items.append(item)
  def removeFront(self):
    return self.items.pop(0)
  def removeRear(self):
    return self.items.pop()
  def empty(self):
    return self.size() == 0
  def size(self):
    return len(self.items)

2. Use the standard library collections. deque

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import deque
class Deque:
  def __init__(self):
    self.items = deque()
  def addFront(self, item):
    self.items.appendleft(item)
  def addRear(self, item):
    self.items.append(item)
  def removeFront(self):
    return self.items.popleft()
  def removeRear(self):
    return self.items.pop()
  def empty(self):
    return self.size() == 0
  def size(self):
    return len(self.items)

Iv. Application

Palindrome (palindrome) is a rhetorical and text game that shares the same words or sentences as reading and reading.

Example:

Madam
Able was I ere I saw elba

Chinese example:

Hua fehua
Everyone for me, everyone for me
If you want to implement a retrieval Verification Algorithm (to verify whether a given string is a retrieval), it is very easy to use the Deque class: to store the string to the double-end queue, at the same time, take out the first and last characters and compare them to determine whether they are equal. If there is a pair of characters, the string is not a background. If all the characters are equal, the string is a background. The Code is as follows:

#! / usr / bin / env python
#-*-coding: utf-8-*-
def palchecker (aString):
   chardeque = Deque ()
   for ch in aString:
     chardeque.addRear (ch)
   while chardeque.size ()> 1:
     first = chardeque.removeFront ()
     last = chardeque.removeRear ()
     if first! = last:
       return False
   return True
if __name__ == '__main__':
   str1 = 'able was i ere i saw elba'
   print ('"% s" is% s palindrome'% (str1, '' if palchecker (str1) else 'not'))
   str2 = u'Everyone is me, I am everybody '
   print (u '"% s"% s is a palindrome'% (str2, u '' if palchecker (str2) else u '不'))
   str3 = u "What's wrong?"
   print (u '"% s"% s is a palindrome'% (str3, u '' if palchecker (str3) else u '不'))

Running result:

$ python palchecker.py
"able was i ere i saw elba" is palindrome
"Everyone for me, I am for everyone" is the palindrome
"What's wrong?" 

I hope this article will help you with Python programming.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.