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();

python基础代码的更多相关文章

  1. Python基础代码1

    Python基础代码 import keyword#Python中关键字 print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'a ...

  2. python基础代码(猜年龄、从最内层跳出多层循环、简单的购物车程序)

    1.猜年龄 , 可以让用户最多猜三次! age = 55 i=0 while i<3: user_guess = int (input ("input your guess:" ...

  3. 【穿插】Python基础之文件、文件夹的创建,对上一期代码进行优化

    在上一期妹子图的爬虫教程中,我们将图片都保存在了代码当前目录下,这样并不便于浏览,我们应该将同一个模特的图片都放在一个文件夹中. 今天我们就简单讲一下Python下如何创建文件.文件夹,今后就可以用上 ...

  4. Python基础教程2上的一处打印缺陷导致的代码不完整#1

    #1对代码的完善的 出现打印代码处缺陷截图: 图片上可以看到,定义的request根本没有定义它就有了.这个是未定义的,会报错的,这本书印刷问题,这个就是个坑,我也是才发现.花了点时间脱坑. 现在发完 ...

  5. python基础1 - 多文件项目和代码规范

    1. 多文件项目演练 开发 项目 就是开发一个 专门解决一个复杂业务功能的软件 通常每 一个项目 就具有一个 独立专属的目录,用于保存 所有和项目相关的文件 –  一个项目通常会包含 很多源文件 在 ...

  6. Python基础篇(三)_函数及代码复用

    Python基础篇_函数及代码复用 函数的定义.使用: 函数的定义:通过保留字def实现. 定义形式:def <函数名>(<参数列表>): <函数体> return ...

  7. python代码注释 - python基础入门(4)

    在 python改变世界,从hello world开始 中我们已经完成了第一个python程序,代码是有了,关键是好像好不知道写的啥玩意? 一.什么是代码注释 代码注释就是给一段代码加上说明,表明这段 ...

  8. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

  9. Python小白的发展之路之Python基础(一)

    Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...

随机推荐

  1. windows 系统防火墙 添加端口号方法

    目前在大部分公司内使用的台式机和部分服务器都采用了Windows操作系统,而我么都知道相当一部分病毒.恶意程序.黑客都是利用扫描端口号,利用开放的端口进行入侵,此时大型企业都会将服务器的系统防火墙打开 ...

  2. springcolud 的学习(四)服务治理. Eureka

    什么是服务治理在传统rpc远程调用中,服务与服务依赖关系,管理比较复杂,所以需要使用服务治理,管理服务与服务之间依赖关系,可以实现服务调用.负载均衡.容错等,实现服务发现与注册.服务注册与发现 在服务 ...

  3. C# 截取字符串方法总结

    第一种:根据单个分隔字符用split截取 string st="GT123_1"; string[] sArray=st.split("_"); //即可得到s ...

  4. Windows 7 下安装 docker

    Windows 7 下需要安装docker toolbox即可(里面打包了docker.oracle virtualbox.Git) 1. 下载 1. 下载路径https://github.com/d ...

  5. ConnectionString属性(网速慢的情况下研究Connect Timeout)

    ConnectionString 类似于 OLE DB 连接字符串,但并不相同.与 OLE DB 或 ADO 不同,如果“Persist Security Info”值设置为 false(默认值),则 ...

  6. mvc和mvvm模式

    一. Mvvm定义 MVVM是Model-View-ViewModel的简写.即模型-视图-视图模型.[模型]指的是后端传递的数据.[视图]指的是所看到的页面.[视图模型]mvvm模式的核心,它是连接 ...

  7. php通过curl发送XML数据,并获取XML数据

    php编程中经常会用到用xml格式传送数据,如调用微信等第三方接口经常用到,这里演示下php以curl形式发送xml,并通过服务器接收 一.发送xml数据 -- postXml.php <?ph ...

  8. 【OGG】OGG的单向复制配置-支持DDL(二)

    [OGG]OGG的单向复制配置-支持DDL(二) 一.1  BLOG文档结构图 一.2  前言部分 一.2.1  导读 各位技术爱好者,看完本文后,你可以掌握如下的技能,也可以学到一些其它你所不知道的 ...

  9. emqx配置ssl

    1.生产自签证书 mkdir /etc/emqttd/certs/ && cd /etc/emqttd/certs/ openssl genrsa -out ca-key.pem 20 ...

  10. Linux命令——jobs、bg、fg、nohup

    参考:Bash基础——工作管理(Job control) jobs -l :除了列出 job number 与命令串之外,同时列出 PID 的号码: -r :仅列出正在背景 run 的工作:-s :仅 ...