假设我们有两种对象,病人和医院:
import random
class Patient:
def __init__(self):
x = random.randint(0,100)
y = random.randint(0,100)
class Hospital:
def __init__(self):
x = random.randint(0,100)
y = random.randint(0,100)假设我们有25名病人和5家医院的名单。
PatientList = []
for p in range(25):
PatientList.append(Patient())
HospitalList = []
for p in range(5):
HospitalList.append(Hospital())其目标是使用属于每个对象的XY坐标来查找与个人病人最近的医院。理想情况下,我们还可以按距离对医院进行排序,或者至少能够在找到最近的医院之后找到第二个最近的,第三个最近的,等等。
发布于 2022-10-23 09:34:54
首先,您需要分配字段:
class Patient:
def __init__(self):
self.x = random.randint(0,100) # use self.x
self.y = random.randint(0,100)
class Hospital:
def __init__(self):
self.x = random.randint(0,100)
self.y = random.randint(0,100)可以使用最小堆对距离进行排序,同时将它们添加到列表中。
import heapq
def closest_hospitals(patient, hospitals, n):
heap = []
for h in hospitals:
# since we are not really concerned with the distance but closeness
# we only need to compare dist^2
dist = (patient.x - h.x)**2 + (patient.y - h.y)**2
heapq.heappush(heap, (dist, hospital)) #this maintains order
# then return n-closest
closest = []
for i in range(n): #you choose n
d, h = heapq.heappop(heap) #returns smallest element
closest.append(h)
return closest发布于 2022-10-23 10:07:32
import numpy as np
import random
class Patient:
def __init__(self):
self.x = random.randint(0, 100) # you need to use self.x to access this variable
self.y = random.randint(0, 100)
class Hospital:
def __init__(self):
self.x = random.randint(0, 100)
self.y = random.randint(0, 100)
PatientList = []
for p in range(25):
PatientList.append(Patient())
HospitalList = []
for p in range(5):
HospitalList.append(Hospital())
# convert data to numpy arrays
PatientArray = np.array([[p.x, p.y] for p in PatientList])
HospitalArray = np.array([[p.x, p.y] for p in HospitalList])
PatientArray = PatientArray[:, np.newaxis] # add an extra dimension
differences = PatientArray - HospitalArray # broadcast
distances = np.linalg.norm(differences, axis=2) # find euclidean distance
proximity_matrix = np.argsort(distances, axis=1) # sort by proximity between patients and hospitals
PatientDict = {} # create a dictionary with patients as keys and list of hospitals (ordered by proximity) as values
# iterate over the proximity matrix and the patient list simultaneously
for hospitals_proximity, patient in zip(proximity_matrix, PatientList):
sorted_hospitals = [HospitalList[i] for i in hospitals_proximity]
PatientDict[patient] = sorted_hospitals现在,PatientDict包含所有患者作为密钥,医院按邻近程度排序为值。
https://stackoverflow.com/questions/74169968
复制相似问题