Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonで優先キューを実装する方法は?


はじめに...

キューモジュールは、マルチスレッドプログラミングに適した先入れ先出し(FIFO)、後入れ先出し(LIFO)のデータ構造を提供します。キューを使用して、データやさまざまな情報を渡すことができます。セッションの詳細、パス、変数、..作成者スレッドと消費者スレッドの間で安全に。ロックは通常、発信者に対して処理されます。

:この説明は、キューの一般的な性質をすでに理解していることを前提としています。そうでない場合は、続行する前にいくつかの参考資料を読むことをお勧めします。

1.基本的なFIFOキューを実装しましょう。

import queue
fifo = queue.Queue()

# put numbers into queue
for i in range(5):
fifo.put(i)

# if not empty get the numbers from queue
print(f"Ouput \n")
while not fifo.empty():
print(f" {fifo.get()} ")

出力

0
1
2
3
4

2.上記の例では、単一のスレッドを使用して、要素が挿入されたのと同じ順序で要素がキューから削除される方法を示しています。

3.基本的なLIFOキューを実装しましょう。

import queue
lifo = queue.LifoQueue()

# put numbers into queue
for i in range(5):
lifo.put(i)

print(f"Ouput \n")
# if not empty get the numbers from queue
while not lifo.empty():
print(f" {lifo.get()} ")

出力

4
3
2
1
0

4.上記の例は、キューに最後に入れられたものがgetによって削除されることを示しています。

5.最後に、優先キューを実装する方法を説明します。

キュー内のアイテムの処理順序は、作成またはキューに追加された順序だけでなく、それらのアイテムの優先度に基づく必要がある場合があります。たとえば、productonで実行されるビジネスクリティカルなジョブには、開発者が印刷したい何かを印刷するジョブよりも高いCPUと優先順位が必要です。 PriorityQueueは、キューの内容の並べ替え順序を使用して、取得するアイテムを決定します。

import queue
import threading

# Class to get the priority and description and validate the priority
class Job:
def __init__(self, priority, description):
self.priority = priority
self.description = description
print('New job:', description)
return

def __eq__(self, other):
try:
return self.priority == other.priority
except AttributeError:
return NotImplemented

def __lt__(self, other):
try:
return self.priority < other.priority
except AttributeError:
return NotImplemented

# create a priority queue and define the priority
q = queue.PriorityQueue()
q.put(Job(90, 'Developer-Print job'))
q.put(Job(2, 'Business-Report job'))
q.put(Job(1, 'Business-Critical Job'))

# process the job
def process_job(q):
while True:
next_job = q.get()
print(f" *** Now, Processing the job - {next_job.description}")
q.task_done()

# define the threads
workers = [
threading.Thread(target=process_job, args=(q,)),
threading.Thread(target=process_job, args=(q,)), ]

# call the threads and join them.
for w in workers:
w.setDaemon(True)
w.start()

q.join()

出力

job: Developer-Print job
New job: Business-Report job
New job: Business-Critical Job

出力

*** Now, Processing the job - Business-Critical Job
*** Now, Processing the job - Business-Report job
*** Now, Processing the job - Developer-Print job

6.この例には、ジョブを消費する複数のスレッドがあり、get()が呼び出されたときのキュー内のアイテムの優先度に基づいて処理されます。処理の順序は、追加された順序に関係なく、ビジネスの重要度に基づいています。


  1. PythonでstrStr()を実装する

    2つの文字列strとsub_strがあるとします。 strでsub_strの最初の出現を見つける必要があります。したがって、文字列strが「helloworld」で、サブ文字列が「lo」の場合、結果は3になります。 これは、Cのstrstr()関数を使用して実行できます。Cのstrstr()に類似した別の関数を設計する必要があります。 これを解決するには、次の手順に従います- i:=0、j:=0、m:=sub_strの長さおよびn:=strの長さ m =0の場合、0を返します i

  2. Pythonでユーザー定義の例外を実装するにはどうすればよいですか?

    Pythonで新しい例外クラスを作成することにより、ユーザー定義またはカスタムの例外を作成します。アイデアは、例外クラスからカスタム例外クラスを派生させることです。ほとんどの組み込み例外は、同じ考え方を使用して例外を強制します。 指定されたコードで、ユーザー定義の例外クラス「CustomException」を作成しました。親としてExceptionクラスを使用しています。したがって、新しいユーザー定義の例外クラスは、他の例外クラスと同じように例外を発生させます。つまり、オプションのエラーメッセージを指定して「raise」ステートメントを呼び出します。 例を見てみましょう。 この例では、ユ