Python | Adjacent Coordinates in N dimension

In this program, we have a tuple consisting of N coordinates of a point. We need to create a Python program that will extract adjacent coordinates in the N dimension.
Submitted by Shivang Yadav, on October 30, 2021

Python programming language is used for a wide variety of tasks which include tasks for performing complex data structure manipulations to working with GUI to some extent. Some applications require the user to work with coordinates, here is one program to extract adjacent coordinates in N dimensions.

Input:
myTuple = (1, 2)

Output:
[[0, 1], [0, 2], [0, 3], [1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3]]

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Extracting adjacent coordinates in N dimension in Python

We have a tuple with n coordinates of a point and we need to find all adjacent coordinates in N dimensions in the python programming language. So for this, we will be finding all the adjacent coordinates of the given point denoted using N element tuple. For this, we need to find all values that are in the range (-1...1) for each element of the tuple and find all possible combinations of the range which will provide all adjacent elements.

In the Python programming language, we can perform this task using the yield along with recursively calling the range for each other element of the tuple.

# Program to extract adjacent coordinates 
# in N dimensions in Python

# Recursive function to find coordinates using yield...
def findAdjPoint(ele, sub = []):
    if not ele:
    	yield sub
    else:
    	yield from [idx for j in range(ele[0] - 1, ele[0] + 2) 
    	    for idx in findAdjPoint(ele[1:], sub + [j])]

# Creating and printing initial tuple (point)
point = (3, 1, 4)
print("The N dimension of point are : " + str(point))

adjCoord = list(findAdjPoint(point))
print("All adjacent Coordinates in N dimension : \n" + str(adjCoord))

Output:

The N dimension of point are : (3, 1, 4)
All adjacent Coordinates in N dimension : 
[
[2, 0, 3], [2, 0, 4], [2, 0, 5], [2, 1, 3], 
[2, 1, 4], [2, 1, 5], [2, 2, 3], [2, 2, 4], 
[2, 2, 5], [3, 0, 3], [3, 0, 4], [3, 0, 5], 
[3, 1, 3], [3, 1, 4], [3, 1, 5], [3, 2, 3], 
[3, 2, 4], [3, 2, 5], [4, 0, 3], [4, 0, 4], 
[4, 0, 5], [4, 1, 3], [4, 1, 4], [4, 1, 5], 
[4, 2, 3], [4, 2, 4], [4, 2, 5]
]

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.