1. 程式人生 > >python學習之每日一題

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