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. 【WEB基础】HTML & CSS 基础入门(2)选取工具:VS2019安装使用

    前面 子曰“工欲善其事,必先利其器”.开始编写HTML代码前,我们该选择一款编辑工具,实际上,HTML作为标记语言,我们甚至可以直接用记事本来编写HTML代码,但记事本实在弱爆了.这里推荐使用Visu ...

  2. Typora基础

    Typora下载网址https://typora.io 一级标题 :# 空格 编写内容 二级标题 2*# 空格 内容 typora快捷键 ctrl+1 =一级标题 有序内容 1.+tab (Q旁边的t ...

  3. javascript ~~ 符号是什么意思呢?

    ~ bitwise NOT 运算符 ~对操作数按位取反,两个的意思即作两次取反操作,其实是等作原数本身(操作数是32整数范围内) ~~(Math.random()*7) 即 var n = Math. ...

  4. mysql的yearweek 和 weekofyear函数

    1.MySQL 的 YEARWEEK 是获取年份和周数的一个函数,函数形式为 YEARWEEK(date[,mode]) 例如 2010-3-14 ,礼拜天 SELECT YEARWEEK('2010 ...

  5. Activiti - eclipse安装Activiti Designer插件

    下载链接:https://www.activiti.org/designer/archived/activiti-designer-5.18.0.zip 如果下载不了,翻墙吧! 参考: https:/ ...

  6. Java -- springboot 配置 freemarker

    1.添加依赖 org.springframework.boot spring-boot-starter-freemarker 2.配置application.properties spring.fre ...

  7. Hive函数集锦

    一.内置运算符 1关系运算符 2.算术运算符 3.逻辑运算符 4.复杂类型函数 5.复杂类型函数应用

  8. Hive性能优化【核心思想、运行模式、并行计算】

    一.核心思想 把HQL当做MapReduce程序去优化. 注意,以下SQL不会转为MapReduce执行: 1.select仅查询本表字段. 2.where仅对本表字段做条件过滤. 二.启动Hive ...

  9. js 获取 对象 属性名称(转载)

    来源:https://www.cnblogs.com/YuyuanNo1/p/9257634.html dataObj = {name : su,age : 26,height : 18cm }; f ...

  10. Order by 默认排序方式

    --ORDER BY 默认排序方式为升序ASC:SELECT * FROM [TABLE_NAME] ORDER BY [COLUMN_NAME] ESC;--升序DESC:SELECT * FROM ...