python期中

%Y/%m/%d,%H:%M:%S

內建指令選擇題

#檢視物件的型態 type() #檢視物件的identity id() #檢視attribute(屬性) dir() #檢視物件說明 help()

Mutable and Immutable

def f1(x,y): a = 0 x[0]= 10 y = 'f1' def f2(x,y): nonlocal a a = 1 y = 'f2' x[1] = 20 def f3(x,y): x[2]= 30 y ='f3' a = 2 print('f3','a:',a,'y:',y) def f4(x,y): x[3]=40 y ='y4' print('f4','a:',a,'y:',y) f4(x,y) f3(x,y) print('f2','a:',a,'y:',y) f2(x,y) print('f1','a:',a,'y:',y) v1 = [1,2,3,4] v2 = 'hello' f1(v1,v2) print(v1,v2)
f4 a: 1 y: y4 #f1 >> f2(nonlocal a) >> f4(Local a) f3 a: 2 y: f3 #f3 >> f3(Local a) f2 a: 1 y: f2 #f1 >> f2(Nonlocal a) f1 a: 1 y: f1 #f1 >> f1(Local a) [10, 20, 30, 40] hello

其他

#高精度計算 import decimal m=decimal.Decimal(input())

formatter

print("{}:{}".format(i),end="") #1.以欄寬w往右靠齊顯示x # abc print('{:{align}{width}}'.format(x, align='>', width=w)) #2.以欄寬w往左靠齊顯示n #123456789 print('{:{align}{width}}'.format(n, align='<', width=w)) #3.以欄寬w往中靠齊顯示x,要有補空白字元 #------abc------ print('{:{sign}{align}{width}}'.format(x, sign=p, align='^', width=w)) #4.以欄寬w往中靠齊顯示n,每千位一個, #--123,456,789-- n=format(n,',')#'{:,}'.format(n) print('{:{sign}{align}{width}}'.format(n, sign=p, align='^', width=w))

string

#1.y是否在x裡(True/False) y in x #2.y在x裡的足標,若沒有輸出-1 x.find(y) #3.以','拆解 x.split(',')#str -> list #4.將x裡前兩個以,隔開的子字串以'---'串接後輸出 s=x.split(',') print(s[0]+'---'+s[1]) #5.檢查x開頭是否為y(True/False) x.startswith(y) #6.檢查x結尾是否為y(True/False) x.endswith(y) #7.將x轉大寫後輸出 x.upper() #8.首字大寫後輸出 x.title() #9.數字(浮點數)判斷 def isnumber(x): try: float(x) return True except ValueError: return False #10.將x裡所有的子字串y改為z print(x.replace(y,z))

sys輸入

for line in sys.stdin:#重複輸入 1. sys.stdin.read() #由sys.stdin輸入,按Enter + Ctrl-Z (Ctrl-D Linux)後傳回讀入字串。 2. x=sys.stdin.readline() # 輸入ㄧ行直到\n (包含\n) 3. x=sys.stdin.readlines() # 輸入多行直到Enter + Ctrl-Z 4. for line in std.stdin.readlines(): print(line) 5. sys.stdout.write(x): #輸出x,沒加\n。 6. sys.stdout.writelines(x): #x為iterable,將x裡的項目逐個輸出。

eval 數學

x<-2
z<-cos(60)*x
print(z)
bye()

import sys import math def cos(x): return math.cos(x/180.0*math.pi) def sin(x): return math.sin(x/180*math.pi) def bye(): sys.exit(0) t={'sin':sin,'cos':cos,'bye':bye,'print':print} while 1: x=input() a=x.split('<-') if len(a)>=2: #變數 t[a[0]]=eval(a[1],t) #造字典 -> 變數,運算 else: #變數 eval(a[0],t) #執行函式

list,set,str,dict

list -> 排序
set -> 比對
str -> 輸出
Counter -> 累計出現次數

#1. s共有幾個字(包含標點符號)? len(s) #2. s共有幾個不同的字(包含標點符號)? len(set(s)) #3. 若list_s=list(s),那麼如何從list_s兜成字串? list_s=list(s) str_s=''.join(list_s)#用''串接 #4. 有哪些字在s與t都出現過(包含標點符號),由小到大逗點隔開輸出? intersection_st=set_s&set_t intersection_st=list(intersection_st) intersection_st.sort() intersection_st=''.join(intersection_st) print(intersection_st) #5. s與t共有多少不同的字(包含標點符號)? intersection_st=set(intersection_st) print(len(set_s|set_t-intersection_st)) #6. 有多少字只出現在s沒出現在t(包含標點符號)? print(len(set_s-intersection_st)) #7. 哪一個字在s與t出現次數最多(包含標點符號),輸出那個字與次數? from collections import Counter st=s+t list(st) st=Counter(st) #get key得到value #st[文字key] = 次數value print("{}:{}".format(max(st,key=st.get),st[max(st,key=st.get)]))

變成list排序

#(1)由小到大輸出,每項資料單獨一列。 s=s.split(',') s.sort() #(2)由大到小輸出,每項資料單獨一列。 s.sort(reverse = True) #(3)由大到小輸出唯一的資料於單獨一列。 s=set(s) s=list(s) s.sort(reverse = True)

讀入dict

dict = {}
dict[key]=value

#1.輸出dict有多少元素於單獨一列。 d=eval(input()) print(len(d)) #2.讀入整數x,輸出x是否在此dict內(keys())於單獨一列 (True/False)。 x=int(input()) print(x in d) #3.讀入整數x,輸出key為x的值是否為0於單獨一列。(True/False/Notexisting (x若不在dict內)) x=input() if x in d: if d[x]==0: print("True") else: print("False") else: print("Notexisting") #4.讀入tuple x,將以x[0]為key,value為x[1]的元素,加入此dict。 x=eval(input()) d[x[0]]=x[1] #5.由小到大輸出dict所有key (一個元素一列)。 for key in sorted(d.keys()): print(key) #6.由小到大輸出dict所有value (一個元素一列)。 for values in sorted(d.values()): print(values) #7.由小到大輸出dict所有(key,value) (一個tuple一列)。 for key in sorted(d.keys()): print("({}, {})".format(key,d[key]))

list

子序列:list[起點 : 終點 : 間隔]
list1.append(list2[i]) -> 插入
list1.remove(list2[i]) -> 刪除
zip(list1,list2) -> 疊代

list1 = list(map(int,input().split(','))) #1. 列出元素及其足標 for i in range(0,len(list1)): print("{}:{}".format(i,list1[i]),end="") #2. 照順序移除(in-place)list1裡小於0的元素至list2 for i in range(0,len(list1)):#插入 if list1[i]<0: list2.append(list1[i]) for i in range(0,len(list2)):#刪除 list1.remove(list2[i]) #3. 使用zip,同時疊代與輸出list1與list2元素 for x, y in zip(list1,list2): print("{}:{}".format(x,y),end="")

建立任意維度的list (deepcopy)

tp[i]=(3,4,5)
5x4x3

import copy def create_mdl(tp, default = None): c = [] a = [] for i in range (len(tp)-1,-1,-1): if i==len(tp)-1: for j in range (1,int(tp[i])+1): a.append(default) else: for j in range (1,int(tp[i])+1): c.append(copy.deepcopy(a)) if j==int(tp[i]): a=copy.deepcopy(c) c=[] return a

comprehension (一行)

list
若x為10,答案為[(3, 4, 5), (6, 8, 10)]。

x = int(input())

#將你的運算方式,填入answer字串,使得eval(answer)會得到所欲答案。
answer = '[(x0,x1,int((x0*x0+x1*x1)**0.5)) for x0 in range(1,x+1) for x1 in range(x0,x+1) if (((x0*x0+x1*x1)**0.5)%1==0) & (((x0*x0+x1*x1)**0.5)<=x)]'

dict
子序列:list [起點 : 終點 : 間隔]
若c為'C',答案為{('A',): 1, ('B',): 1, ('C',): 1, ('A', 'B'): 2, ('A', 'C'): 2, ('B', 'C'): 2, ('A', 'B', 'C'): 3}

from itertools import combinations  
s = [chr(i) for i in range(65, 91)]#建字母表
s = s[:ord(c)-64:]    #切割list
answer = '{result:i for i in range(1,ord(c)-64+1) for result in combinations(s, i)}'

lambda函數 filter, map, reduce

lambda 函式
filter 過濾
map 映射
reduce 累積操作

from functools import reduce import math a = list(map(int,input().split(','))) # expr1寫出使用filter,選擇a裡正的且為3的倍數。 expr1=filter(lambda x: (x%3==0)&(x>0),a) # expr2寫出使用map,將a裡的元素的對映至math.exp(-a) expr2=map(lambda x: math.exp(-x),a) # expr3寫出使用reduce計算a裡的元素絕對值的和 expr3=reduce(lambda x,y: abs(x)+abs(y),a)

修飾器

def pretty(o_func): def n_func(*a,**k): return '$'+o_func(*a,**k)+'$' return n_func
def pretty(o_func): return lambda *a,**k:'$'+o_func(*a,**k)+'$'
@pretty def f1(): return 'f1' print(f1())

檔案操作

import os.path name=os.path.basename('C:\\Python\\Sourcec:\\Python\\Sources\\prog1.py') #文件名 dir_name=os.path.dirname('C:\\Python\\Sourcec:\\Python\\Sources\\prog1.py') #資料夾 os.path.join(name,dir_name) #位址相加 os.getcwd() #當前工作目錄 os.chdir('C:\\') #更改當前工作目錄 os.listdir(os.getcwd()) #列出當前工作目錄

Datetime

import datetime import time tmstr_first = str(input()) tmstr_sec = str(input()) #str -> time tm_first=datetime.datetime.strptime(tmstr_first,"%Y-%m-%d %H:%M:%S") tm_sec=datetime.datetime.strptime(tmstr_sec,"%Y-%m-%d %H:%M:%S") d = tm_sec - tm_first print(d.days,d.seconds) print(int(d.total_seconds()))

依據檔案大小搜尋檔案

for f in list_file_by_time("c:\\users",10): printf(f) ... ('c:\\users\\adm\\.ipython\\profile_default\\history.sqlite', ....
import os from os.path import join, getsize, getatime, getmtime, getctime def list_file_by_size(directory, n): for root, dirs, files in os.walk(directory): for full_file_name in files: full_file_name=join(root,full_file_name) #路徑+名字 filesize=getsize(full_file_name)#檔案大小 if filesize>=n: yield (full_file_name, filesize)

依據天數差距搜尋檔案

import os import datetime from os.path import join, getsize, getatime, getmtime, getctime def list_file_by_time(directory, d): for root, dirs, files in os.walk(directory): for full_file_name in files: full_file_name=join(root,full_file_name) #路徑+名字 lest_time=datetime.datetime.fromtimestamp(getmtime(full_file_name))#修改時間 today=datetime.datetime.today() d_len=today-lest_time if d_len.days<d: yield (full_file_name, lest_time)

class

rect = Rectangle(x0,y0,width,height)
可建構一個涵蓋(x0,y0)-(x0+width,y0+height)的矩形
使用@property製作rectangle.area計算其面積

rect2=Rectangle(x1,y1,width2,height2)

rect3=rect1 | rect2 #rect3為涵蓋包含rect1與rect2區域的最小矩形

rect4=rect1 & rect2#rect4為剛好涵蓋rect1與rect2重疊區的矩形

override member function str
使得print(rect1) #會顯示Rectangle: (x0,y0)-(x0+width,y0+height)

rect == eval(repr(rect)) #為True

class Rectangle: def __init__(self,x0,y0,width,height):#存變數 self.x0 = x0 self.y0 = y0 self.width = x0+width self.height = y0+height @property def area(self):#定義函式 return self.width*self.height def __or__(self,other):#定義運算符 x=min(self.x0,other.x0) y=min(self.y0,other.y0) width=max(self.width,other.width) height=max(self.height,other.height) return 'Rectangle: ('+str(x)+','+str(y)+')-('+str(width)+','+str(height)+')' def __and__(self,other):#定義運算符 x=max(self.x0,other.x0) y=max(self.y0,other.y0) width=min(self.width,other.width) height=min(self.height,other.height) return 'Rectangle: ('+str(x)+','+str(y)+')-('+str(width)+','+str(height)+')' def __eq__(self,other):#定義運算符 if (self.x0 == other.x0) & (self.y0 == other.y0) & (self.width == other.width) & (self.height == other.height) : return True else: return False def __str__(self):#定義運算符 return 'Rectangle: ('+str(self.x0)+','+str(self.y0)+')-('+str(self.width)+','+str(self.height)+')' def __repr__(self):#定義運算符 x0=self.x0 y0=self.y0 width=self.width height=self.height return "Rectangle({},{},{},{})".format(x0,y0,width,height)