Try sorting your own objects with priority queue in Python

Execution environment

python 3.7.3

Thing you want to do

Use the priority queue using python. I want to apply it a little, such as sorting my own objects.

What is Priority Queue?

Also called a priority queue. The scene to use is when you want to sort while the number of elements changes. Or when you want to add an element to the list while keeping the sorted state.

Since various other people have written reference articles, I will omit the details. (https://qiita.com/ell/items/fe52a9eb9499b7060ed6)

I want to sort my own objects.

Try sorting objects of Name class that have two attributes, first_name and last_name, according to various conditions.

First, generate the following class as a base.


class Name(object):
    def __init__(self,first_name,last_name):
        self.first_name = first_name
        self.last_name = last_name
    
    def __lt__(self,other):
        return other.first_name > self.first_name
    
    def __repr__(self):
        return self.first_name + " " + self.last_name

The heart of this time is a special method called lt. You can set what it means to be smaller than you. (There are many other special methods as well. Please check them out. https://blog.codecamp.jp/python-class-code)

Let's actually sort using heapq.

from heapq import heapify,heappush,heappop
name1 = Name("james","smith")
name2 = Name("john","johnson")
name3 = Name("robert","williams")
name4 = Name("michael","brown")
name5 = Name("william","jones")
name6 = Name("david","brown")
name7 = Name("james","miller")
name8 = Name("david","davis")

name_list = [name1,name2,name3,name4,name5,name6,name7,name8]
heapify(name_list)
for i in range(len(name_list)):
    print(heappop(name_list))

Please refer to the official document for details on how to use heapq. → https://docs.python.org/ja/3/library/heapq.html

Click here for execution results david brown david davis james miller james smith john johnson michael brown robert williams william jones

Since the lt method is set to judge the size based only on the first name, you can see that the first names are arranged in ascending order.

Try to apply

Next, as a practice, try sorting by first name first, then by last name in the opposite direction. The expected output is:

david davis david brown james smith james miller john johnson michael brown robert williams william jones

The first names are listed in ascending order, but the last names are listed in descending order. See the code below for an example implementation of this.

class Name(object):
    def __init__(self,first_Name,last_Name):
        self.first_Name = first_Name
        self.last_Name = last_Name
    
    def __lt__(self,other):
        if other.first_Name == self.first_Name:
            return other.last_Name < self.last_Name
        else:
            return other.first_Name > self.first_Name
    
    def __repr__(self):
        return self.first_Name +" "+ self.last_Name


from heapq import heapify,heappush,heappop
name1 = Name("james","smith")
name2 = Name("john","johnson")
name3 = Name("robert","williams")
name4 = Name("michael","brown")
name5 = Name("william","jones")
name6 = Name("david","brown")
name7 = Name("james","miller")
name8 = Name("david","davis")

name_list = [name1,name2,name3,name4,name5,name6,name7,name8]
heapify(name_list)
for i in range(len(name_list)):
    print(heappop(name_list))

Thank you for watching until the end If you like, please LGTM (Looks Good To Me) If you make a mistake, please point it out.

Recommended Posts

Try sorting your own objects with priority queue in Python
Try to improve your own intro quiz in Python
[Python] logging in your own module
Try HeloWorld in your own language (with How to & code)
Ant book in python: Priority queue self-implementation
Try logging in to qiita with Python
Create your own Linux commands in Python
Easily use your own functions in Python
Publish your own Python library with Homebrew
Try text mining your diary in Python
Get your own IP address in Python
[Cloudian # 5] Try to list the objects stored in the bucket with Python (boto3)
Try to make your own AWS-SDK with bash
Track objects in your video with OpenCV Tracker
Argument implementation (with code) in your own language
Make your own module quickly with setuptools (python)
Try working with Mongo in Python on Mac
Import your own modules in Grasshopper's Python development
Try scraping with Python.
Basic sorting in Python
Queue processing in Python
Try gRPC in Python
Try 9 slices in Python
Flow of creating your own package with setup.py with python
Memo to create your own Box with Pepper's Python
Create your own Big Data in Python for validation
Create your own Random Dot Stereogram (RDS) in Python.
Let's call your own C ++ library with Python (Preferences)
Try implementing associative memory with Hopfield network in Python
Algorithm learned with Python 18th: Sorting (stack and queue)
Try embedding Python in a C ++ program with pybind11
Use the CASA Toolkit in your own Python environment
Try to put LED in your own PC (slightly)
[Road to intermediate Python] Define in in your own class
Try running python in a Django environment created with pipenv
Try scraping the data of COVID-19 in Tokyo with Python
Scraping with selenium in Python
Working with LibreOffice in Python
Scraping with chromedriver in python
Until you can install your own Python library with pip
Debugging with pdb in Python
Try Python output with Haxe 3.2
Run the intellisense of your own python library with VScode.
Working with sounds in Python
Sorting image files with Python (2)
Scraping with Selenium in Python
Sorting image files with Python (3)
Equivalence of objects in Python
Techniques for sorting in Python
Try LINE Notify in Python
Scraping with Tor in Python
Tweet with image in Python
Sorting image files with Python
Combined with permutations in Python
Stack and Queue in Python
Try running Python with Try Jupyter
Try implementing Yubaba in Python 3
Recognize red objects with python
Try face recognition with Python
[Cloudian # 6] Try deleting the object stored in the bucket with Python (boto3)
Create your own graph structure class and its drawing in python