按题目要求的步骤去做就行
注意两点:
1.对n维向量求欧式距离用
def count_o(point1,point2):
res=sum((a-b)**2 for a,b in zip(point1,point2))
return pow(res,0.5)
这个代码
2.对标签出现次数排序时,用
count_sorted=sorted(count.items(),key=lambda x:x[1],reverse=True)
这个代码,关键点是
key=lambda x:x[1],只按值排序
和
reverse=True,因为sorted默认按升序排,也就是从左到右是值从小到大排,我们要的是值从大到小,且
要使排序是稳定的,相同值的原始的相对顺序不能改变,这是题目要求(sorted自动满足这一点)
import sys
data=input().split()
k=int(data[0])#最近邻近个数
m=int(data[1])#样本数
n=int(data[2])#n维特征
s=int(data[3])#类别个数
def count_o(point1,point2):
res=sum((a-b)**2 for a,b in zip(point1,point2))
return pow(res,0.5)
feature=list(map(float,input().split()))#特征数
items=[]
while(m>0):
data=list(map(float,input().split()))
items.append(data)
m-=1
#print(item)
#[[0.2, 0.1, 0.0], [0.3, 0.0, 0.0], [0.0, 0.4, 1.0], [0.6, 0.6, 1.0], [0.05, 0.02, 0.0], [0.9, 0.9, 1.0]]
dis=[]
idx=-1
for item in items:
idx+=1
dis.append((count_o(feature,item[:n]),idx))
dis_sorted=sorted(dis)
k_dis_mark=[]
idx=0
while(k>0):
target_index=dis_sorted[idx][1]
k_dis_mark.append(items[target_index][n])
idx+=1
k-=1
count={}
for i in k_dis_mark:
if i not in count:
count[i]=1
else:
count[i]+=1
count_sorted=sorted(count.items(),key=lambda x:x[1],reverse=True)
print(int(count_sorted[0][0]),count_sorted[0][1])