Sometimes, while working with Python lists, we can have a problem in which we need to perform the grouping of all the coordinates which occur adjacent on a matrix, i.e horizontally and vertically at distance 1. This is called Manhatten distance. This kind of problem can occur in competitive programming domain. Let’s discuss certain way in which this task can be performed.
Input : test_list = [(4, 4), (6, 4), (7, 8)]
Output : [[(7, 8)], [(6, 4)], [(4, 4)]]
Input : test_list = [(4, 4), (5, 4)]
Output : [[(5, 4), (4, 4)]]
Method : Using
product() + groupby() + list comprehension
The combination of above methods can be used to solve this problem. In this, we perform the task of grouping of elements using groupby() and check for pairs using product(). The logic driving this solution is similar to union find algorithm.
The original list is : [(4, 4), (6, 4), (7, 8), (11, 11), (7, 7), (11, 12), (5, 4)] The grouped elemets : [[(6, 4), (5, 4), (4, 4)], [(7, 8), (7, 7)], [(11, 12), (11, 11)]]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
- Python - Adjacent Coordinates in N dimension
- Python | Calculate geographic coordinates of places using google geocoding API
- Python | Reverse Geocoding to get location on a map using geographic coordinates
- Python | Convert location coordinates to tuple
- Python - Character coordinates in Matrix
- Displaying the coordinates of the points clicked on the image using Python-OpenCV
- Parallel Coordinates Plot using Plotly in Python
- Python Program to convert complex numbers to Polar coordinates
- PyQt5 – How to get Label coordinates ?
- Python - Group Sublists by another List
- Python | Group elements at same indices in a multi-list
- Python | Group by matching second tuple value in list of tuples
- Python | Group tuples in list with same first value
- Python | Group list elements based on frequency
- Python | Swap Name and Date using Group Capturing in Regex
- Python | Group consecutive list elements with tolerance
- Python | Group elements on break positions in list
- Python | Group strings at particular element in list
- Python | Group and count similar records
- Python | Binary Group Tuple list elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.