Details about the queue of Python algorithm applications and python queues

Source: Internet
Author: User

Details about the queue of Python algorithm applications and python queues

Queue)

A queue is a First-In-First-Out (FIFO, First-In-First-Out) linear table. In a specific application, a linked list or array is usually used. A queue is only allowed on the backend (called rear) insert and delete the queue at the front end (called front). The queue operation method is similar to that of the stack, the only difference is that the queue only allows new data to be added on the backend (excerpt from Wikipedia ).

Queue Interface

A queue requires at least the following interfaces:

Interface Description
Add (x) Join
Delete () Team-out
Clear () Clear queue
IsEmpty () Determine whether the queue is empty
IsFull () Determine if the queue is not full
Length () Current Queue Length
Capability () Queue capacity

However, in Python, you can use the deque function in the collections module. The deque function provides all the interfaces of the queue. Let's take a look at the APIS provided by the queue deque function:

collections.dequeIt is a dual-end queue, that is, both the left and right sides can be imported and output.

Method Description
Append (x) Add an element to the right of the queue
Appendleft (x) Add an element to the left of the queue
Clear () Delete all elements from the queue
Copy () Returns a copy of the shortest copy.
Count (value) Number of times the returned value appears in the queue
Extend ([x ..]) Extend the right side of the queue using iteratable Elements
Extendleft ([x...]) Extend the right side of the queue using iteratable Elements
Index (value, [start, [stop]) The first index of the returned value. If the value does not exist, ValueError is thrown.
Insert (index, object) Insert an object before the index
Maxlen Obtains the maximum length of a queue.
Pop () Delete and return the rightmost Element
Popleft () Delete and return the leftmost Element
Remove (value) Delete the first value found
Reverse () All elements in the queue are flipped
Rotate () Rotate the queue n step to the right (n = 1 by default). If n is negative, rotate it to the left.

Now let's test the use of these APIs in Python.

Team-up operations

>>> From collections import deque # create a queue >>> q = deque ([1]) >>> qdeque ([1]) # Add an element to the queue> q. append (2) >>> qdeque ([1, 2]) # Add an element to the leftmost of the queue >>> q. appendleft (3) >>> qdeque ([3, 1, 2]) # Join multiple elements at the same time >>> q. extend ([4, 5, 6]) >>> qdeque ([3, 1, 2, 4, 5, 6]) # team up multiple elements at the leftmost> q. extendleft ([7, 8, 9]) >>> qdeque ([9, 8, 7, 3, 1, 2, 4, 5, 6])

Team-out operations

# Delete the last one in the queue >>> q. pop () 6 >>> qdeque ([9, 8, 7, 3, 1, 2, 4, 5]) # Delete the leftmost element in the queue >>> q. popleft () 9 >>> qdeque ([8, 7, 3, 1, 2, 4, 5])

Other APIs

# Clear the queue >>> qdeque ([8, 7, 3, 1, 2, 4, 5]) >>> q. clear () >>> qdeque ([]) # judge whether the queue is empty >>> not qTrue # obtain the maximum queue length >>> q = deque ([1, 2], 10) >>> q. maxlen10 # view the number of times an element appears >>> q. extend ([1, 1, 1]) >>> q. count (1) 4 # view the current queue length >>> len (q) 6 # determine whether the queue is full >>> q. maxlen = len (q) False # queue element inversion >>> q = deque ([, 5], 5) >>> q. reverse () >>> qdeque ([5, 4, 3, 2, 1], maxlen = 5) # view the index corresponding to the element >>> q. index (1) 4 # Delete the first matched element >>> qdeque ([5, 4, 3, 2, 1], maxlen = 5) >>> q. remove (5) >>> qdeque ([4, 3, 2, 1], maxlen = 5) # rotate the element position >>> qdeque ([4, 3, 2, 1], maxlen = 5) >>> q. rotate (2) >>> qdeque ([2, 1, 4, 3], maxlen = 5) >>> q. rotate (1) >>> qdeque ([3, 2, 1, 4], maxlen = 5) # use a negative number >>> q. rotate (-1) >>> qdeque ([2, 1, 4, 3], maxlen = 5)

Instance

Binary Coefficient

Question

Write a program to calculate the number of series at Layer K in the binary coefficient table (Yang Hui triangle)

 1 1 1 1 2 11 3 3 1......

Ideas

  1. Store the coefficient of row K in the queue
  2. Rank the coefficient of the K-layer (the last one in each line does not go out of the team), calculate the coefficient of the K + 1 layer, add it to the end of the team, and finally add a 1 to the end of the team, then it becomes k + 1 line.

Solution code

#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ from collections import dequedef yanghui (k): "": param k: layers in the Yang Hui triangle: return: coefficient of the K layer "q = deque ([1]) # create a queue, starting from 1 by default for I in range (k ): # number of layers to be searched for during Iteration for _ in range (I): # Number of times q is required for a loop. append (q. popleft () + q [0]) # Add the first number to the second number in the queue and assign the value to q at the end of the queue. append (1) # after each query, add a 1 return list (q) result = yanghui (3) print (result) to the rightmost of the queue)

Division of non-conflicting Subsets

Question

When a zoo moves, it will take away N animals. tigers and lions will join everyone, elephants and rhinos will fight in a cage, wild boar and wild dog will fight in a cage, now we need to design an algorithm so that the animals in the same cage do not fight each other.

Ideas

  1. Team all animals in order
  2. Create a cage (SET) and team out an animal. If there is no conflict with the animal in the cage, add it to the cage. If there is a conflict, add it to the end of the team and wait for the new cage to enter.
  3. Due to the features of the queue's first-in-first-out feature, if the index of the current team-out animal is not greater than that of the previous team-out animal, it means that all the animals in the current queue have tried to enter and cannot enter the current cage, the mail cage (SET) is created at this time)

Solution code

#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ from collections import dequedef division (m, n): ": param m: conflict matrix: param n: Several animals: return a stack containing all cages "res = [] # create a stack q = deque (range (n )) # initialize the queue with the animal serial number pre = n # The subscript of the previous animal while q: cur = q. popleft () # Start an animal from the queue if pre> = cur: # whether to create a cage res. append ([]) # create a cage # whether the current animal conflicts with the animal in the cage for a in res [-1]: # if m [cur] [a]: # conflicting q. append (cur) # re-import the break else at the end of the queue: # no conflict between the current animal and all the animals in the current cage res [-1]. append (cur) # Put the current animal in the top cage pre = cur # return resN = 9R ={# conflict ing table (1, 4), (4, 8), (1, 8), (1, 7), (8, 3), (1, 0), (0, 5), (1, 5 ), (3, 4), (5, 6), (5, 2), (6, 2), (6, 4 ),} M = [[0] * N for _ in range (N)] # fl relational matrix M. 0 indicates no conflict for I, j in R: M [I] [j] = M [j] [I] = 1 #1 indicates the conflicting result = division (M, N) print (result)

Digital Transformation

Question

For a positive integer a and B, only 1, 1, and 2 can be added to a. How many operations can be performed on a to obtain B?

For example:

  1. A = 3, B = 11: 11 can be obtained through 322-operations;
  2. A = 5, B = 8: You can get 8 through (5-1) * 2, 2 operations;

Ideas

This topic uses the breadth-first search to find the shortest path for a to B State migration. For each State s, it can be converted to s + 1, S-1, s * 2:

  1. Team initialization status;
  2. One status s is displayed, and s + 1, S-1, and s * 2 are included;
  3. Repeat the second step until the status s is B;

Solution code

#! /Use/bin/env python # _ * _ coding: UTF-8 _ * _ from collections import dequedef atob (a, B): "": param a: Start Number: param B: the number after the final conversion: return: minimum matching times "q = deque ([(a, 0)]) # a = current number, 0 = number of operations checked = {a} # data that has been checked while True: s, c = q. popleft () if s = B: break if s <B: # if s + 1 not in checked: # If the number to be calculated + 1 is not in the data set that has been checked, q. append (s + 1, c + 1) # Number of computations + 1, number of conversions + 1 checked. add (s + 1) # add the calculated number to the checked set if s * 2 not in checked: q. append (s * 2, c + 1) checked. add (s * 2) if s> 0: # the number to be calculated is greater than 0 if s-1 not in checked: q. append (s-1, c + 1) checked. add (s-1) return q. popleft () [-1] result = atob (3, 11) print (result)

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.