• Last Updated : 11 Jun, 2021

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.

Python3

 # Python3 code to demonstrate working of# Group Adjacent Coordinates# Using product() + groupby() + list comprehensionfrom itertools import groupby, product def Manhattan(tup1, tup2):    return abs(tup1 - tup2) + abs(tup1 - tup2) # initializing listtest_list = [(4, 4), (6, 4), (7, 8), (11, 11),                     (7, 7), (11, 12), (5, 4)] # printing original listprint("The original list is : " + str(test_list)) # Group Adjacent Coordinates# Using product() + groupby() + list comprehensionman_tups = [sorted(sub) for sub in product(test_list, repeat = 2)                                         if Manhattan(*sub) == 1] res_dict = {ele: {ele} for ele in test_list}for tup1, tup2 in man_tups:    res_dict[tup1] |= res_dict[tup2]    res_dict[tup2] = res_dict[tup1] res = [[*next(val)] for key, val in groupby(        sorted(res_dict.values(), key = id), id)] # printing resultprint("The grouped elements : " + str(res))
Output
The original list is : [(4, 4), (6, 4), (7, 8), (11, 11), (7, 7), (11, 12), (5, 4)]
The grouped elements : [[(6, 4), (5, 4), (4, 4)], [(7, 8), (7, 7)], [(11, 12), (11, 11)]]

My Personal Notes arrow_drop_up