webdancer's Blog

python连接MySQL数据库

python连接MySQL可以使用MySQLdb,数据库API规范可以参考PEP249,描述了类和应具有的属性和方法。MySQL的操作可以参考MySQL tutorial。

1.环境配置。

在Ubuntu11.10下面,自带python,但是没有MySQL,MySQLdb,所以首先安装MySQL,MySQLdb.

sudo apt-get install mysql-server
sudo apt-get install python-mysqldb

2.熟悉MySQL的基本操作。

连接Server:

mysql -h host -u user -p

输入Queries:

select version();

创建,使用database:

create database students;
use students;

查看数据库,表:

show databases;
show tables;

创建表:

create table webgrades(class varchar(10),number varchar(15), name varchar(20),grade int);

向表插入内容:

insert into webgrades values ('1','001','Justin',76);

从表查找内容:

select * from webgrades;

更多的内容参考MySQL tutorial。

3.python使用MySQLdb连接Server。

#! /usr/bin/env python
# -*- coding: utf8 -*-
import MySQLdb

#connect to the server
con=MySQLdb.connect(host='localhost',user='root',passwd='qweqwe',db='students')
#get cursor
cursor=con.cursor()
#execute the sql
operator="""insert into webgrades values (%s,%s,%s,%s)"""
para=[('1','200201000101','王丽',95),
      ('2','200201000201','赵宝刚',88),
      ('3','200201000301','杜玉',92)
      ]
cursor.executemany(operator,para)

#close the connection
con.close()

当然,更多的有关python连接数据库的知识参考python.org。

求中位数

统计学中,中位数代表一个样本中的一个数值,其可将数值集合划分为相等的上下两部分。

实数$$x_1,x_2,......,x_n$$按大小顺序(升序,降序皆可)排列为$$x_1^,,x_2^,,......,x_n^,$$,实数数列$$x_1,x_2,......,x_n$$的中位数$$Q_\frac{1}{2}(x)$$为:

$$Q_\frac{1}{2}(x)$$=$$\lfloor\frac{(n+1)}{2}\rfloor$$

明确了概念后我们可以来解决怎么找中位数了。

算法1:按照定义所说的,首先排序,然后直接返回$$Q_\frac{1}{2}(x)$$即可。

算法2:在《算法导论》中介绍了如何可以在期望线性时间找到中位数。

 思想是:1.按照快排的思想,不断的随机分割。

                 2.如果随机分割的返回值恰是我们找的,可以返回该位置的数。

                 3.如果不满足,比较一下返回值与我们找的位置的大小,递归的进行下去,直到满足1.

算法3:

思想是: 1.利用快速排序的思想,不断的的分割。不过没有用递归。

用python实现了一下上面的算法,结果:

  algorithm1(ms) algorithm2(ms) algorithm3(ms)
$$10^3$$ 0 0 0
$$10^4$$ 9 19 20
$$10^5$$ 140 120 70
$$10^6$$ 2149 1689 780
$$10^7$$ 27480 21479 12480

 

 

 

 

 

 

参考:

1.http://zh.wikipedia.org/wiki/%E4%B8%AD%E4%BD%8D%E6%95%B0

2.算法导论。




Host by is-Programmer.com | Power by Chito 1.2.6 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee