from heapq import *;
from collections import *;
import random as rd;
import operator as op;
import re; data = [2,2,6,7,9,12,34,0,76,-12,45,79,102];
s = set(); for num in data:
s.add(data.pop(0));
if s.__len__() == 4:
break; heap = [];
for n in s:
heappush(heap,n); print(heap); for num in data:
if num > heap[0]:
heapreplace(heap,num); print(nlargest(4,heap)) def file2matrix(path,dimension):
with open(path,'r+') as fr:
lines = fr.readlines();
num_lines = len(lines);
return_mat = np.zeros((num_lines,dimension));
classLabel = []; index = 0;
for line in lines:
contents = line.strip().split(' ');
li = contents[:dimension];
li = list(map(float,li));
return_mat[index,:] = li; if(contents[-1] == 'small'):
classLabel.append(0);
elif(contents[-1] == 'middle'):
classLabel.append(1)
elif (contents[-1] == 'large'):
classLabel.append(2)
index += 1; return return_mat, classLabel; #mat,label = file2matrix('G:\\test.txt',3); import collections;
print(dir(collections)) class MyObject:
def __init__(self,score):
self.score = score; def __repr__(self):
return "MyObject(%s)" % self.score; objs = [MyObject(i) for i in range(5)];
rd.shuffle(objs);
print(objs); g = op.attrgetter("score");
scores = [g(i) for i in objs];
print("scores: ",scores);
print(sorted(objs,key = g)); l = [(i,i*-2) for i in range(4)]
print ("tuples: ", l)
g = op.itemgetter(1)
vals = [g(i) for i in l]
print ("values:", vals)
print ("sorted:", sorted(l, key=g)) class MyObj(object):
def __init__(self, val):
super(MyObj, self).__init__()
self.val = val
return def __str__(self):
return "MyObj(%s)" % self.val def __lt__(self, other):
return self.val < other.val def __add__(self, other):
return MyObj(self.val + other.val) a = MyObj(1)
b = MyObj(2) print(op.lt(a, b)) print(op.add(a, b)) items = [('A', 1),('B', 2),('C', 3)]
regular_dict = dict(items);
order_dict = OrderedDict(items);
print(regular_dict);
print(order_dict); # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2) fig = plt.figure(figsize=(8,4),dpi=120)
plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
plt.plot(x,z,"b--",label="$cos(x^2)$")
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("PyPlot First Example")
plt.ylim(-1.2,1.2)
plt.legend()
#plt.show() f = plt.gcf();
all_lines = plt.getp(f.axes[0],'lines');
print(all_lines[0]) fig = plt.figure()
line1 = Line2D([0,1],[0,1], transform=fig.transFigure, figure=fig, color="r")
line2 = Line2D([0,1],[1,0], transform=fig.transFigure, figure=fig, color="g")
fig.lines.extend([line1, line2])
fig.show() def autonorm(dataSet):
minVals = dataSet.min(0);
maxVals = dataSet.max(0);
ranges = maxVals - minVals;
rows = dataSet.shape[0];
ranges = np.tile(ranges,(rows,1));
dataSet = dataSet - np.tile(minVals,(rows,1));
normData = dataSet / ranges;
return normData; def classify(inX,path,k):
#1.文件到矩阵的映射
labels,dataSet = file2matrix(path);
#2.矩阵归一化处理
dataSet = autonorm(dataSet);
#3.计算欧式距离
distance = dataSet - inX;
distance = np.square(distance);
distance = distance.sum(axis=1);
distance = np.sqrt(distance);
print(distance);
#4.对距离排序
sortdisIndices = distance.argsort();
#5.取前k个,加载到dict中,然后对dict排序,取首个值
classCount = {};
for index in range(k):
label = labels[sortdisIndices[index]];
print(label)
classCount[label] = classCount.get(label,0) + 1; sortedDict = sorted(classCount.items(),key=op.itemgetter(1),reverse=True);
return sortedDict[0][0]; def file2matrix(filepath):
with open(filepath,'r+') as fr:
lines = fr.readlines();
num_lines = len(lines);
classLabelVector = [];
dimension = len(lines[0].strip().split(" "))-1;
dataSet = np.zeros((num_lines,dimension)); index = 0;
for line in lines:
contents = line.strip().split(" ");
li = contents[:dimension];
li = list(map(float,li));
dataSet[index,:] = li; if contents[-1] == 'largeDoses':
classLabelVector.append(3);
elif contents[-1] == 'smallDoses':
classLabelVector.append(2);
elif contents[-1] == 'didntLike':
classLabelVector.append(1);
index += 1; return classLabelVector,dataSet; def main(): inX = np.array([1.2,1.0,0.8]);
label = classify(inX,"E:\\Python\\datingTestSet.txt",3);
print("class:",label); if __name__ == '__main__':
main();

最新文章

  1. Runtime实战之定制TabBarItem大小
  2. 学习mysql
  3. Animations功能(区别于Transitions)
  4. [2015hdu多校联赛补题]hdu5348 MZL&#39;s endless loop
  5. Knockout 新版应用开发教程之Computed Observables
  6. table.appand(行数据) datagrid分页
  7. jQuery 遍历 - map() 方法
  8. PHP 布尔类型
  9. servlet的提交
  10. 移动端下网页border:1px显示
  11. mongodb 3.4 集群搭建升级版 五台集群
  12. springboot之banner
  13. mysql如何执行关联查询与优化
  14. Linux网站运维工程师基础大纲
  15. OpenCV探索之路(十七):Mat和IplImage访问像素的方法总结
  16. Redis 十分钟快速入门
  17. AngularJS入门之动画
  18. Java 如何重写对象的 equals 方法和 hashCode 方法
  19. 将浮点数保持几位小数,尾数舍入的Format函数
  20. Windows运行常用命令(win+R)

热门文章

  1. C语言 - 可变参数再stm32中的应用
  2. Windows下使用MongoDb的经验
  3. AWS--Lamdba
  4. Spring Security 解析(一) —— 授权过程
  5. js-Date对象(九)
  6. window.requestAnimationFrame()的使用,处理更流畅的动画效果
  7. testNG helloWorld
  8. [LeetCode] 78. 子集 ☆☆☆(回溯)
  9. [Java] Eclipse中复制全限定名(Copy Qualified Name)的效果
  10. centos7.6在线yum安装docker-ce