Python code to find all combinations of pairs for a given function's values

I have multiple sets of coordinates and I am looking to calculate the distance between each pair. Despite being able to compute the distances, I am struggling to display the corresponding coordinate pairs in my program.

import itertools
import math
point1 = (1,1,0.5)
point2 = (3,3,1)
point3 = (2,0.5,2)
point4 = (0.5,2,1)

points = [(point1),(point2),(point3),(point4)]
pointsPairs = itertools.combinations(points, 2)
for pair in pointsPairs:
 x1 = pair[0][0]
 y1 = pair[0][1]
 z1 = pair[0][2]
 x2 = pair[1][0]
 y2 = pair[1][1]
 z2 = pair[1][2]

"""Define a function to calculate the distance between two sets of coordinates"""
def calculate_distance(x1,y1,x2,y2,z1,z2):
   dist=math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2-z1)**2)
   return dist
d=calculate_distance(x1,y1,x2,y2,z1,z2)
print d

This results in:

2.87228132327
1.87082869339
1.22474487139
2.87228132327
2.69258240357
2.34520787991

I want to format the output like this for each combination:

"Distance between point1 and point2 is"
  2.87228132327

Answer №1

Prior to running your loop, a dictionary can be created with coordinates as the key and the corresponding name (using indexes that start at 1) as the value:

points_dict = {k:"point_{}".format(i) for i,k in enumerate(points,1)}

Within your loop, you can simply retrieve the name from the coordinates generated by the combinations function:

print("calculating distance between {} and {}".format(points_dict[pair[0]],points_dict[pair[1]]))

Implementing this approach results in the following output:

calculating distance between point_1 and point_2
2.8722813232690143
calculating distance between point_1 and point_3
1.8708286933869707
calculating distance between point_1 and point_4
1.224744871391589
calculating distance between point_2 and point_3
2.8722813232690143
calculating distance between point_2 and point_4
2.692582403567252
calculating distance between point_3 and point_4
2.345207879911715

Answer №2

Primarily, the identification of your points is lacking in the data structures that have been implemented. I made some modifications to your code to incorporate the names of the points:

import itertools
import math

"""Establishing the distances between the atoms"""
def calculate_distance(x1,y1,x2,y2,z1,z2):
   dist=math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2-z1)**2)
   return dist

point1 = (1,1,0.5,'point1')
point2 = (3,3,1,'point2')
point3 = (2,0.5,2,'point3')
point4 = (0.5,2,1,'point4')

points = [(point1),(point2),(point3),(point4)]
pointsPairs = itertools.combinations(points, 2)
for pair in pointsPairs:
 x1 = pair[0][0]
 y1 = pair[0][1]
 z1 = pair[0][2]
 x2 = pair[1][0]
 y2 = pair[1][1]
 z2 = pair[1][2]
 d=calculate_distance(x1,y1,x2,y2,z1,z2)
 p1=pair[0][3]
 p2=pair[1][3]
 print "The distance between '%s' and '%s' is" % ( p1, p2 ) 
 print d

The outcome displays as follows:

The distance between 'point1' and 'point2' is
2.87228132327
The distance between 'point1' and 'point3' is
1.87082869339
The distance between 'point1' and 'point4' is
1.22474487139
The distance between 'point2' and 'point3' is
2.87228132327
The distance between 'point2' and 'point4' is
2.69258240357
The distance between 'point3' and 'point4' is
2.34520787991

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The power trio: Python, Numpy, and OLS working together

Although the code provided is close to what I need, there is a minor adjustment required. I aim to replace c[1] with c[1:] in order to perform regression against all the x variables instead of just one. However, upon making this change and adding the neces ...

Developing a multithreaded approach to locating elements using Selenium

Looking to optimize my script's performance, I decided to implement multithreading for the more time-consuming parts, particularly the locator calls. However, I encountered "CannotSendRequest" and "ResponseNotReady" exceptions from the threads. Is th ...

What is the best way to navigate between various websites using selenium and python?

I've almost completed my script that automatically generates a new PayPal account. However, I'd like to enhance the script by pulling information from another website before closing the driver. Specifically, I want the script to navigate to Gmai ...

Sending JSON data with Python and fetching the response

I've been working on a Python script to make a post request, but I'm not receiving any response. Everything seems correct in my code, so I suspect there might be an issue with the service itself causing the lack of response. Can anyone spot if th ...

What causes the translation of text within HTML tags to occur when attempting to retrieve it during Web Scraping?

Exploring the world of web scraping, I am currently immersed in a small project. In this snippet of code, I am capturing the HTML content and storing it in a variable named soup. source=requests.get(URL) soup=BeautifulSoup(source.text,'html.parser&apo ...

Error: The function model() was expecting 3 arguments, but it received 5 arguments instead

When using the following setup, everything runs smoothly with odeint: import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint v0 = 10.0 k1 = 0.5 k2 = 0.35 def model(x,t): dx0 = v0 - k1*x[0] dx1 = k1*x[0] - k2*x[1] ...

Python Selenium Error: session ID is not valid

After attempting to initiate the web driver, randomly putting it to sleep, and then closing it, I encountered an error with the message "invalid session id." Can anyone offer a solution to this issue? Please The code snippet in question is as follows: ...

Issue with running Selenium script from console compared to CRON, encountering Geckodriver error

My Selenium script is set up to run from an SH file. When I manually execute the SH file from the console, everything works perfectly. However, when I schedule the file to run from a Cron job, it fails. This is the content of my SH file: #!/bin/sh expor ...

Tips for halting the execution of a scheduled airflow DAG

I made a mistake and accidentally set up a basic DAG job to run every 5 minutes. This is the command I used: airflow backfill jobs -s 2017-05-01 -e 2017-06-07 When I checked the airflow Webserver GUI, it started running multiple backfilled jobs. I attemp ...

Unexpectedly large dataset for the Test and Training Sets

Currently, I am in the process of developing a predictive model using linear regression on a dataset containing 157673 records. The data is stored in a CSV file and follows this format: Timestamp,Signal_1,Signal_2,Signal_3,Signal_4,Signal_5 2021-04-13 ...

Excel automation with PyXLL using Python 3 Formula tips

(Using Python3, Sublime Text3, Anaconda, and XLWINGS) I have created a Google Doc of an Excel spreadsheet to help clarify my question. Click here to access the Google Doc I am seeking assistance in creating a process that moves data from Excel to Python ...

Utilizing Selenium WebDriver in Python to locate and interact with WebElements

Currently, I am utilizing Selenium for real-time web scraping. However, I am encountering issues searching for a specific WebElement even though the documentation indicates that it is feasible. while True: try: member = self.pdriver.find_all(" ...

What is the best way to create a function in Clojure that is able to store its previous input for future reference?

While browsing through a forum, I stumbled upon an interesting problem posted by a student. The task was to find the longest sequence of characters where the next symbol occurs after the current one. For example, given the string "abzbac", the output would ...

Increasing value based on condition in a pandas DataFrame effectively

In my pandas dataframe, I have a desire to compare the values in Var1 and Var2 import pandas as pd data = [['foo', 'foo', 1613030200], \ ['foo', 'foo', 1613030300], ['foo', 'bar', ...

Steps for calculating total credit hours within a sublist

Within this nested array, I am looking to calculate the total sum of credit hours. The credit hours can be found at positions [2] and [5]. Is there a way to accomplish this task using a Python for loop without relying on Numpy? marks = [ [ "MR. ...

Fixing issues with unicode characters not displaying correctly in a 2.7.10 application running on TravisCI

I'm having trouble displaying unicode characters in a test runner using Python 2.7.10 on TravisCI. When running the code locally on macOS, everything works fine: # -*- coding: utf-8 -*- from __future__ import unicode_literals class MyTestCase(unitt ...

Issue with Python list indexing within a for loop containing an inner while loop

Provided below is my optimized code: from collections import Counter class Solution: def minWindow(self, s: str, t: str) -> str: left = 0 right = float("inf") ref = Counter(t) necessary_count = sum(ref.values()) ...

Poorly executed polynomial regression graph

Looking for some help as I navigate my way through this new adventure. Despite searching and reading various blogs, I haven't been able to find a solution. If you could take the time to explain both the problem and the solution, it would be greatly ap ...

Guide on predicting market fluctuations with the arch_model.predict() function

After utilizing the arch library to fit a GARCH model, I am facing an issue with predicting future volatility beyond tomorrow. Adjusting the horizon parameter only results in new columns named 'h.' showing up. What steps should I take to address ...

Is there a way to determine the number of lines in a CSV file in Python before loading

I recently started learning Python and I need to import dataframes from different CSV files. I have a specific business logic that relies on the number of rows in the CSV file. Is there a way for me to determine the total number of rows in a CSV file wit ...