python基础代码
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基础代码的更多相关文章
- Python基础代码1
Python基础代码 import keyword#Python中关键字 print(keyword.kwlist) ['False', 'None', 'True', 'and', 'as', 'a ...
- python基础代码(猜年龄、从最内层跳出多层循环、简单的购物车程序)
1.猜年龄 , 可以让用户最多猜三次! age = 55 i=0 while i<3: user_guess = int (input ("input your guess:" ...
- 【穿插】Python基础之文件、文件夹的创建,对上一期代码进行优化
在上一期妹子图的爬虫教程中,我们将图片都保存在了代码当前目录下,这样并不便于浏览,我们应该将同一个模特的图片都放在一个文件夹中. 今天我们就简单讲一下Python下如何创建文件.文件夹,今后就可以用上 ...
- Python基础教程2上的一处打印缺陷导致的代码不完整#1
#1对代码的完善的 出现打印代码处缺陷截图: 图片上可以看到,定义的request根本没有定义它就有了.这个是未定义的,会报错的,这本书印刷问题,这个就是个坑,我也是才发现.花了点时间脱坑. 现在发完 ...
- python基础1 - 多文件项目和代码规范
1. 多文件项目演练 开发 项目 就是开发一个 专门解决一个复杂业务功能的软件 通常每 一个项目 就具有一个 独立专属的目录,用于保存 所有和项目相关的文件 – 一个项目通常会包含 很多源文件 在 ...
- Python基础篇(三)_函数及代码复用
Python基础篇_函数及代码复用 函数的定义.使用: 函数的定义:通过保留字def实现. 定义形式:def <函数名>(<参数列表>): <函数体> return ...
- python代码注释 - python基础入门(4)
在 python改变世界,从hello world开始 中我们已经完成了第一个python程序,代码是有了,关键是好像好不知道写的啥玩意? 一.什么是代码注释 代码注释就是给一段代码加上说明,表明这段 ...
- python之最强王者(2)——python基础语法
背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...
- Python小白的发展之路之Python基础(一)
Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...
随机推荐
- MPAndroid 的学习
1.MPAndroid 的github的地址: https://github.com/PhilJay/MPAndroidChart#documentation 2.使用步骤: 在build.gradl ...
- P2613 【模板】有理数取余 (数论)
题目 P2613 [模板]有理数取余 解析 简单的数论题 发现并没有对小数取余这一说,所以我们把原式化一下, \[(c=\frac{a}{b})\equiv a\times b^{-1}(mod\ p ...
- 设计模式--Bulider模式
起因:最近在做统计计算,创建的实体中属性比较多,都是一些数值,一开始是通过get.set方法进行赋值,占用了很多业务代码方法的长度,可读性不太好,后来改用了添加构造器的方式,稍显精简了一点,但是每次赋 ...
- Spring框架的核心概念是什么?需要掌握的知识点都有哪些?
Spring其主要精髓 就是IOC和AOP.掌握好了这两点对于理解Spring的思想颇有意义. IOC(英文 Inversion of Control)就是控制反转的意思.就是把新建对象(new Ob ...
- java实现在线预览--poi实现word、excel、ppt转html
java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...
- Python使用numpy进行数据转换
一.测试数据 二.代码实现 # -*- coding: utf-8 -*- """ Created on Sun Jul 7 11:35:01 2019 加载数据时对指定 ...
- Vue常用工具类方法 总结
1.利用Cookie,来设置接口携带的‘token’ 执行命令npm install js-cookie,在js工具类中引入, /** @format */ import Cookie from 'j ...
- 线程中的join方法,与synchronized和wait()和notify()的关系
什么时候要用join()方法? 1,join方法是Thread类中的方法,主线程执行完start()方法,线程就进入就绪状态,虚拟机最终会执行run方法进入运行状态.此时.主线程跳出start方法往下 ...
- MongoDB 分片的原理、搭建、应用 (转)
一.概念: 分片(sharding)是指将数据库拆分,将其分散在不同的机器上的过程.将数据分散到不同的机器上,不需要功能强大的服务器就可以存储更多的数据和处理更大的负载.基本思想就是将集合切成小块,这 ...
- iOS 测试在应用发布前后的痛点探索以及解决方案
作者-芈 峮 前言 iOS 开发从 2010 年开始在国内不断地升温,开发和测试相关的问题不绝于耳.iOS 测试主要涉及哪些内容?又有哪些挑战呢?带着疑问我们开始第一个大问题的讨论. iOS 测试的范 ...