python学习之每日一题

2017.2.6 第1天

有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

import itertools
lis = list(itertools.permutations([1, 2, 3, 4], 3))
print lis
print len(lis)

2017.2.7 第2天

企业发放的奖金根据利润提成。

利润(I):低于或等于10万元时,奖金可提10%;

10万到20万之间时,高于10万元的部分,可提成7.5%;

20万到40万之间时,高于20万元的部分,可提成5%;

40万到60万之间时,高于40万元的部分,可提成3%;

60万到100万之间时,高于60万元的部分,可提成1.5%;

高于100万元时,超过100万元的部分按1%提成;

从键盘输入当月利润I,求应发放奖金总数?

arr1 = [[10, 10*0.1], [20, 10*0.075], [40, 20*0.05], [60, 20*0.03], [100, 40*0.015]]
arr2 = [[0, 0.1], [10, 0.075], [20, 0.05], [40, 0.03], [60, 0.015], [100, 0.01]]
value = input("please enter a value:")
m = sum([b for a, b in arr1 if a < value])
n = max([[a, b] for a, b in arr2 if a < value])
sum1 = m+(value-n[0])*n[1]
print(sum1)

2017.2.8 第3天

输入某年某月某日,判断这一天是这一年的第几周,第几天,星期几?

import datetime
import time

a = raw_input("Please enter a date in the form of yyyymmdd:")
t = time.strptime(a, "%Y%m%d")
y, m, d = t[0:3]
day = (datetime.date(y, m, d))
print day.strftime("%j")
print day.strftime("%W")
print day.strftime("%w")

2017.2.9 第4天

获取指定目录下所有文件的名称 

import tkFileDialog
import os

path = tkFileDialog.askdirectory()
print os.listdir(path)

2017.2.10 第5天

1-18共18个数字,随机产生数字和奖品的对应关系,分别是1个一等奖、2个二等奖,3个三等奖,14个纪念奖,
随机抽取一个数字,每次不重复,输出号码及所中奖类型。
格式如下:
1、程序执行
已经初始化完成!
请按任意键抽奖...(按任意键)
2、按任意键后
您抽中的号码是12 ,恭喜您中了一等奖
还有2个二等奖,3个三等奖,14个纪念奖
请按任意键抽奖...

import random
a = ['一等奖']+['二等奖']*2+['三等奖']*3+['纪念奖']*14
b = []
c = range(20)
i = 0
random.shuffle(a)

while True:
    ch = input("请按任意键抽奖...(按回车)")
    num = random.randint(1, 19)
    while num in b:
        num = random.randint(1, 19)
    b.append(num)
    print("您抽中的号码是", num, ",恭喜您中了", a[num])
    if len(b) >17:
       print("还剩下")
       for i in set(c).difference(set(b)):
           print(i,"号", a[i])
       break
2017.2.12 第7天
生成一个html页面,另存为index.html

2017.2.13 第8天
输入六个整数,如果输入非整数提示输入“错误请重新输入”,把输入内容由小到大输出

# -*- coding:utf-8 -*-
numList = []
while len(numList) < 6:
    num = raw_input("请输入:\n")
    if num.isdigit():
        numList.append(num)
    else:
        print("错误!请重新输入!!\n")
numList.sort()
print numList
2017.2.14 第9天
使用sqlite3创建test.db数据库,建立表person(id 整型 主键,name 字符型 不为空,Gender M/F,Birthdate 日期型),向表格中插入三条数据(至少含一条女生信息),将表中录入的女生信息输出出来 
import sqlite3
# 连接
conn = sqlite3.connect('d://test.db')
cur = conn.cursor()
# 建表
sql = 'create table person(Id INTEGER PRIMARY KEY , Name VARCHAR(255) NOT NULL ,Gender VARCHAR(255) ,Birthday DATE)'
cur.execute(sql)
# 插入数据
for t in [(1, 'a', 'F', '2017-02-14'), (2, 'b', 'M', '2017-02-13'), (3, 'c', 'F', '2017-02-12')]:
    cur.execute('insert into person VALUES (?,?,?,?)', t)
    conn.commit()
# 查询
cur.execute("SELECT * from person where Gender = 'F'")
conn.commit()
print cur.fetchall()
2017.2.15 第10天
打开指定的Excel文件,读取指定的工作表的指定的多个行和列的数据并输出

# -*- coding:utf-8 -*-
# 创建
wb = xlwt.Workbook()
sheet = wb.add_sheet('new sheet')
# sheet.write(行,列,值), 插入数据,行和列从0开始
sheet.write(1, 2, 'first')
sheet.write(2, 2, 'second')
sheet.write(3, 2, 'third')
wb.save('test.xls')
# 打开
xls = xlrd.open_workbook('test.xls')
"""
# 通过索引顺序获取
table = xls.sheets()[0]
table = xls.sheet_by_index(0)
"""
# 通过名称获取
table = xls.sheet_by_name('new sheet')
# 输出第2行第3列的值
print table.row_values(1, 2, 3)
2017.2.16 第11天
建立一个student类,使用@staticmethod和@classmethod分别建立static_f和class_f两个方法,调用体会差异
class student:
    @staticmethod
    def static_f():
        print 'staticmethod,没有参数,调用方法:student.static_f()'
    @staticmethod
    def static_f(name):
        print 'staticmethod,参数名:' + name +'调用方法:student.static_f('name')'
    @staticmethod
    def static_f(cls):
        print 'staticmethod,参数名:' + cls +'调用方法:student.static_f('cls'),这里的cls只是一个普通的参数,不能用student.static_f()调用'
    
    @classmethod
    def class_f(cls):
        print 'classmethod,调用方法:student.class_f()'

    @classmethod
    def class_f(cls, name):
        print 'classmethod,参数名:' + name +'调用方法:student.class_f('name')'
2017.2.17 第12天
 连续输入多个字符,最小不能少于4个,最大不超过20,只能包含0-9的数字,a-z的小写字母,A-Z的大写字母,判断出不符合要求的字符 

2017.2.18 第13天
将bmp格式的图片转成JPG格式

2017.2.19 第14天

 将一个文件用zip压缩,压缩后的文件名同于解压前的文件名  
# -*- coding:utf-8 -*-
import zipfile
import os
import tkFileDialog

path = tkFileDialog.askopenfilename(title='选择一个文件', filetypes=[('所有文件','.*')])
# fil = os.path.basename(path)
f = zipfile.ZipFile('1.zip', 'w', zipfile.ZIP_DEFLATED)
f.write(path)
f.close()

2017.2.20 第15天

 输入x1,y1 x2,y2  x3,y3三个坐标构成一个三角形,随机输入一个坐标判断是否在三角形范围内 

2017.2.21 第16天
 将0到5亿之内的偶数找出来,打印出执行时间,将结果存成num.txt 
import numpy as np
import time

start = time.clock()
a = np.arange(500000000)
b = a[::2]
np.set_printoptions(threshold='nan')
print b
np.savetxt('num', b, fmt='%s', newline='\n')
end = time.clock()
print('Running time: %s Seconds' % (end-start))
2017.2.22 第17天
写一个decorator,在函数调用的前后打印出‘begin’和‘end’
# 函数不含参数
def dec(func):
    def _deco():
        print 'begin'
        func()
        print 'end'
    return _deco

@dec
def newfunc():
    print('this is a func')
# 函数带参数
def dec(func):
    def _dec(a, b):
        print 'begin'
        func(a, b)
        print 'end'
    return _dec
@dec
def newfunc(a,b):
    print(a,b)

newfunc(2, 3)
newfunc(3, 4)

2017.2.23 第18天

创建一个简单http webserver服务器,端口是8080,通过在浏览器访问http://127.0.0.1:8080可以获得一个helloword页面

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
Handler = SimpleHTTPRequestHandler
Server = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8080
server_address = ('127.0.0.1', port)
Handler.protocol_version = Protocol
httpd = Server(server_address, Handler)

print("Serving HTTP")
httpd.serve_forever()

2017.2.27 第19天

用pyqt5设计标题为“Hello world”有一个名为“发送”和“关闭”的按钮的窗口,点击发送按钮弹出“hello world!”的对话框,点击关闭按钮退出程序。

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()
    def initUI(self):
        self.sendbtn =  QtGui.QPushButton(self)
        self.sendbtn.setText('send')
        self.sendbtn.move(10,10)
        self.sendbtn.clicked.connect(self.setText)
        self.exitbtn = QtGui.QPushButton(self)
        self.exitbtn.setText('exit')
        self.exitbtn.move(10, 40)
        self.exitbtn.clicked.connect(self.close)
        self.show()

    def setText(self):
        qtm = QtGui.QMessageBox
        qtm.information(self,'','hello,world')
def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
        main()

2017.2.28 第20天

用pyqt5设计标题为“input”的窗口,可以输入姓名,选择性别,点击保存存入名为input.txt文件,试着生成EXE

2017.3.1 第21天

两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。
已抽签决定比赛名单。有人向队员打听比赛的名单。
a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单

2017.3.2 第22天

打开新浪主页,分析页面中URL链接,去除重复的和外部域名的内容将结果存入文本文件中

import re
import requests

r = requests.get('http://www.sina.com')
data = r.text
# 找链接
link_list = re.findall(r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')", data)
# link_list = re.findall('"(http?://*sina.*?)"', data)

# 去重
list1 = {}.fromkeys(link_list).keys()
# 去外部域名
for url in list1:
   if url.find('sina') == -1:
       list1.remove(url)
# 链接个数
print len(link_list)
# 符合要求的链接个数
print len(list1)
file = open('data.txt', 'w')
file.write(str(list1))
file.close()
2017.3.3 第23天

使用matplotlib绘制直线、矩形区域

http://blog.csdn.net/qq_37482544/article/details/60357246

2017.3.4 第24天

手工建一个test.html文件,将文件转成PDF文件

import pdfkit
HTML_NAME = "d:\\test.html"

f = open(HTML_NAME, 'w')
htmltext = """
<html>
<head></head>
<body>
<p>this is a test.html</p>
</body>
</html>
"""
f.write(htmltext)
f.close()
pdfkit.from_url('test.html','test.pdf')
pdfkit.from_string(htmltext, 'out.pdf')

2017.3.5 第25天

打开文本文件读取内容,并生成word文档,文件名为test.doc


2017.3.7 第26天

利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。 
str = raw_input("enter a string:")
def f(x):
    if x == -1:
        return ''
    else:
        return str[x] + f(x-1)
print(f(len(str)-1))


2017.3.8 第27天

使用Flask,访问mysql数据库,建立一个表,并插入一条数据

2017.3.9 第28天


2017.3.10 第29天

建立person类,及派生man类,体会构造、析构、重载、重写的用法

2017.3.11 第30天

删除list里面的重复元素,并降序排列输出

l1 = [1,2,3,4324,32,3,2,1,5,3,6,4]
l2 = {}.fromkeys(l1).keys() #去重
l3 =  sorted(l2,reverse=True) #降序排列
print l3

2017.3.12 第31天

设计函数接受文件夹的名称作为输入参数,返回该文件夹中文件的路径,以及其包含文件夹中文件的路径

# coding :utf-8
import os
import tkFileDialog

path = tkFileDialog.askdirectory()
def print_directory_contents(sPath):
    for sChild in os.listdir(sPath):
        sChildPath = os.path.join(sPath,sChild)
        if os.path.isdir(sChildPath):
            print_directory_contents(sChildPath)
        else:
            print sChildPath

print_directory_contents(path)

2017.3.13 第32天

有四个线程1、2、3、4。线程1的功能就是输出A,线程2的功能就是输出B,以此类推......... 现在有四个文件file1,file2,file3, file4。初始都为空。
现要让四个文件呈如下格式:
file1:A B C D A B....
file2:B C D A B C....
file3:C D A B C D....
file4:D A B C D A....

2017.3.14 第33天

一句代码求list中奇数的平方和

l = [1,2,3,4,5,6,34,1]
s = sum(x ** 2 for x in l if x % 2 != 0)
print s

2017.3.15 第33天

实现‘rot13’加密。即把字母表中每个字母用其后的第13个字母代替。举例来说,a将替换为n,X将替换为K

apl = ''.join([chr(i) for i in range(65,123)])
b = apl.encode("rot-13")
print b

2017.3.18 第34天

打印一张乘法口诀表

print('\n'.join([ ' '.join([ "%d*%d=%2s" %(y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))
2017.3.20 第35天

2017.3.21 第36天

 用Python画一个饼状图 甘肃林业资源图 荒漠化30% 林地40% 湿地10% 其他20% 

# coding:utf-8
import matplotlib.pyplot as plt

labels = [u'荒漠化', u'林地', u'湿地', u'其他']
X = [30, 40, 10, 20]

fig = plt.figure()
plt.pie(X, labels=labels, autopct='%1.2f%%')
plt.title(u'甘肃林业资源图')
plt.show()

2017.3.22 第37天

用Python要求输出国际象棋棋盘

import turtle
def draw_square(this_turtle, size,FT):
    this_turtle.pendown()
    this_turtle.fill(FT)
    for i in range(4):
        this_turtle.forward(size)
        this_turtle.right(90)
    this_turtle.fill(False)
    this_turtle.penup()

window = turtle.Screen()
myturtle = turtle.Turtle()
square_size = 30
x = -300
y = 200
myturtle.goto(x,y)

for j in range(8):
    for i in range(8):
        if (i+j) % 2 == 0:
            draw_square(myturtle, square_size,True)
        else:
            draw_square(myturtle, square_size,False)
        myturtle.forward(square_size)
    myturtle.goto(x,y-square_size*(j+1))
turtle.done()

2017.3.23 第38天

有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

ms=int(input("请输入要查询的月份数:"))
ms_1=0
ms_2=1
for i in range(1,ms+1):
    ms_0 = ms_1 + ms_2
    ms_2 = ms_1
    ms_1 = ms_0
print("第 "+str(ms)+" 个月的兔子总数是:"+str(ms_0 * 2))

2017.3.25 第39天

连接oracle 11g forgansuforest数据库,读取表F_FOR_TABLE_COL_COMMENTS(table_name column_name,comments),循环读取表F_FOR_TABLE_COL_COMMENTS,按要求生成后缀为.sql的文本文件(每行格式如:comment on column tablename.columnname  is “用户名”),tablename,columnname,用户名来自数据库

import cx_Oracle
import csv
tns=cx_Oracle.makedsn('10.2.10.199',1521,'orcl')
orcl = cx_Oracle.connect('ForGansuForestSharding','654321',tns)
curs = orcl.cursor()
csv_file_dest = "test.sql"
outputFile = open(csv_file_dest,'w')
output = csv.writer(outputFile)
sql = "select TABLE_NAME,COLUMN_NAME,COMMENTS from F_FOR_TABLE_COL_COMMENTS"
curs.execute(sql)
for row_data in curs:
    output.writerow(['comment on column ' + str(row_data[0]) + '.' + str(row_data[1]) + ' is \''+ str(row_data[2]) + '\''])
outputFile.close()

2017.3.26 第40天

模仿ping命令,输入ip 判断该地址是否联通。

import os
ip = raw_input("please enter an ip address:")
return1 = os.system('ping -n 1 -w 1 %s'%ip)
if return1:
    print 'ping %s is fail'%ip
else:
    print 'ping %s is ok'%ip
2017.3.27 第41天
画三维图像 曲面图和散点图
# 散点图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = [1, 1, 2, 2]
Y = [3, 4, 4, 3]
Z = [1, 2, 1, 1]
ax.scatter(X,Y,Z)
plt.show()
# 曲面图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X = [1, 1, 2, 2]
Y = [3, 4, 4, 3]
Z = [1, 2, 1, 1]
ax.plot_trisurf(X, Y, Z)
plt.show() 
官网中的一个matplotlib示例:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()










2017.3.31 第42天
unittest module 编写单元测试
被测模块,保存为cal.py
class cal:
  def sum(self, x, y):
    return x+y
单元测试
import unittest
import cal
class mytest(unittest.TestCase):
  def setUp(self):
    self.tclass = cal.cal()
  def tearDown(self):
    pass
  def testsum(self):
      self.assertEqual(self.tclass.sum(1, 2), 3)
if __name__ =='__main__':
  unittest.main()
2017.4.4 第43天
 学习实现决策树算法  

2017.4.12 第44天
公鸡5文钱一只,母鸡3文钱一只,小鸡3只一文钱,用100文钱买一百只鸡其中公鸡,母鸡,小鸡都必须要有,问公鸡,母鸡,小鸡要买多少只刚好凑足100文钱
# 赋值
cock_price,hen_price,chick_price = 5, 3, 1/3
# 计算
cock_MaxNum, hen_MaxNum, chick_MaxNum = range(100/cock_price)[1:], range(100/hen_price)[1:], range(int(100/chick_price))[1:]
items = [(cock, hen, chick) for cock in cock_MaxNum for hen in  hen_MaxNum[1:] for chick in  chick_MaxNum[1:]
       if int(cock * cock_price + hen * hen_price + chick * chick_price)==100 and chick % 3 == 0 and cock + hen + chick==100]
# 输出
print('总数:'+str(len(items)))
print('='* 32)
print('%-10s%10s%20s' % ('公鸡','母鸡','小鸡'))
print('-'* 32)
for c in items:
   print('%-5s%10s%15s' % c)
print('-'*32)
2017.4.24 第45天
 用Python写一个WebService, 调用天气的webservice,显示天气信息 

2017.4.25 第46天
 写一个用到Python自省(反射)的例子
# coding:utf-8
class Cat(object): # 类,Cat指向这个类对象
    def __init__(self, name='kitty'):
        self.name = name
    def sayHi(self): #  实例方法,sayHi指向这个方法对象,使用类或实例.sayHi访问
        print self.name, 'says Hi!' # 访问名为name的字段,使用实例.name访问

cat = Cat('kitty')
print cat.name # 访问实例属性
cat.sayHi() # 调用实例方法

print dir(cat) # 获取实例的属性名,以列表形式返回
if hasattr(cat, 'name'): # 检查实例是否有这个属性
    setattr(cat, 'name', 'tiger') # same as: a.name = 'tiger'
print getattr(cat, 'name') # same as: print a.name
getattr(cat, 'sayHi')() # same as: cat.sayHi()








  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值