2020年1月28日 星期二
CH13 演算法(全)
Python 序列 List
其他語言 陣列 Array
巴斯卡三角形:
1. 使用二維陣列
2. 使用 2 個一維陣列
3. 使用 1 個一維陣列
4. 使用公式
5. 使用遞迴
------------- 巴斯卡三角形 二維序列
p=[[0]*30 for i in range(20)]
n=10
p[0][1]=1
for i in range(1,(n+1)+1):
for j in range(1,(n+1)+1):
p[i][j]=p[i-1][j]+p[i-1][j-1]
for i in range(0,n+1):
for j in range(0,(i+1)+1):
print("%4d" %(p[i][j]),end='');
print()
0 1
0 1 1
0 1 2 1
0 1 3 3 1
0 1 4 6 4 1
0 1 5 10 10 5 1
0 1 6 15 20 15 6 1
0 1 7 21 35 35 21 7 1
0 1 8 28 56 70 56 28 8 1
0 1 9 36 84 126 126 84 36 9 1
0 1 10 45 120 210 252 210 120 45 10 1
------------- 巴斯卡三角形 2 個一維序列
list01=[];list02=[]
for i in range(15):
list01.append(0)
list02.append(0)
list01[1]=1
print(list01[1:2])
c=0
while c<10:
for i in range(15):
list02[i]=list01[i-1]+list01[i]
for i in range(15):
list01[i]=list02[i]
c=c+1
print(list02[1:c+2])
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
[1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1]
------------- 巴斯卡三角形 2個二維序列
def pascal(n):
if n<=0:
return
else:
row=[1]
for i in range(n):
print(row)
p=row[:]
for j in range(1,len(row)):
row[j]=p[j]+p[j-1]
row.append(1)
pascal(10)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
------------- 巴斯卡三角形 一維
n=int(input("幾層:"))
plist=[]
for i in range(1,n+1):
plist.append(1)
for j in range(i-2,0,-1):
#print(i,j,plist[j],plist[j-1],end='')
plist[j]=plist[j]+plist[j-1]
#print(plist)
print("行號:",i,plist)
幾層:10
行號: 1 [1]
行號: 2 [1, 1]
行號: 3 [1, 2, 1]
行號: 4 [1, 3, 3, 1]
行號: 5 [1, 4, 6, 4, 1]
行號: 6 [1, 5, 10, 10, 5, 1]
行號: 7 [1, 6, 15, 20, 15, 6, 1]
行號: 8 [1, 7, 21, 35, 35, 21, 7, 1]
行號: 9 [1, 8, 28, 56, 70, 56, 28, 8, 1]
行號: 10 [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
四則運算 中序轉後序
2020年1月27日 星期一
Python基礎 --Python 網路爬蟲王者 --佳魁資訊
-------------------------------------- 開始之前
IDLE Python GUI 是一個功能完備的程式 IDE ( Integrated Development Environment 整合式開環境 )
Python Shell Python 的互動模式
Tab 建,自動補全關鍵字
Alt + P 回復到上一次編輯的 Python 程式
Alt + N 相反
--------------------------------------3.1 Python 哲學
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
提姆·彼得斯(Tim Peters)撰寫的《 Python之禪》
美麗勝於醜陋。
顯式勝於隱式。
簡單勝於復雜。
複雜勝於復雜。
扁平比嵌套更好。
稀疏勝於密集。
可讀性很重要。
特殊情況還不足以打破規則。
儘管實用性勝過純度。
錯誤絕不能默默傳遞。
除非明確地保持沉默。
面對模棱兩可的想法,拒絕猜測的誘惑。
應該有一種-最好只有一種-顯而易見的方法。
儘管除非您是荷蘭人,否則一開始這種方式可能並不明顯。
現在總比沒有好。
儘管從來沒有比現在“正確”好。
如果實現難以解釋,那是個壞主意。
如果實現易於解釋,則可能是個好主意。
命名空間是一個很棒的主意-讓我們做更多這些吧!
--------------------------------------3.2 輸入與輸出
3.2.1 print
>>> print("Hello Python!")
Hello Python!
name="kk"
print("Hello %s ,Nice to meet you!" %name) # %s 字串
Hello kk ,Nice to meet you!
age=27
print("You are %d !" %age) # %d 數字
You are 27 !
n=100
print("You print is %r !" %n) # %r 不知列印類型
n="ABC"
print("You print is %r !" %n)
You print is 100 !
You print is 'ABC' !
3.2.2 input
n=input("Enter any content:")
print ("Your input is %r" %n)
Enter any content:Tom
Your input is 'Tom'
3.2.3 引號與註釋
Python 不區分單引號與雙引號
# 單行註釋
"""或 ''' 三個引號表示多行註釋,不區分單引號與雙引號
--------------------------------------3.3 分支與循環
3.3.1 if 敘述
a=2
b=3
if a>b:
print("a max!")
else:
print("b is max!")
b is max!
name="Tom"
if name=="Tom": # 相等 == , 不相等 !=
print("Tom,you are on duty today.")
else:
print("Please call Tom to duty")
Tom,you are on duty today.
string="Hello World"
if "Hello" in string: # not in 表示不包含
print("Contain")
else:
print("Not Contain")
Contain
a=True
if a:
print("a is True")
else:
print("a is not True")
a is True
results=72
if results >= 90:
print('優秀')
elif results >= 70:
print('良好')
elif results >= 60:
print('及格')
else:
print('不及格')
良好
3.3.2 for 敘述
print(i)
H
e
l
l
o
W
o
r
l
d
fruits=["banana","apple","mango"] #字典
for i in fruits:
print(i)
banana
apple
mango
for i in range(4+1): #進行一定次數的循環
print(i)
0
1
2
3
4
#range(start,end[,step])預設從0開始循環,也可設定起始位置和步進值,Python3 range()是一個陣列
for i in range(1,9+1,2):
print(i)
1
3
5
7
9
--------------------------------------3.4陣列 [ ]與字典 { }
3.4.1 陣列
>>> lists=[1,2,3,'a',5]
>>> lists
[1, 2, 3, 'a', 5]
>>> lists[0]
1
>>> lists[4]
5
>>> lists[4]='b'
>>> lists[4]
'b'
>>> lists.append('c')
>>> lists
[1, 2, 3, 'a', 'b', 'c']
3.4.2 字典
>>> dicts={'na':'Tom','pwd':123456}
>>> dicts.keys()
dict_keys(['na', 'pwd'])
>>> dicts.values()
dict_values(['Tom', 123456])
>>> dicts.items()
dict_items([('na', 'Tom'), ('pwd', 123456)])
>>> for i in dicts.items():
print(i)
('na', 'Tom')
('pwd', 123456)
>>> for k,v in dicts.items():
print("dicts key is %r" %k)
print("dicts values is %r" %v)
dicts key is 'na'
dicts values is 'Tom'
dicts key is 'pwd'
dicts values is 123456
>>> key=['b','a','c','e','d']
>>> value=['2','1','3','5','4']
>>> for k,v in zip(key,value): #zip 方法合併2個 List 為 Dictionary
print(k,v)
b 2
a 1
c 3
e 5
d 4
-------------------------------------- 3.5 函數、類別和方法
3.5.1 函數
def add(a,b):
print(a+b)
add(3,5)
8
def add(a,b):
return (a+b)
print(add(3,5))
8
def add(a=1,b=2):
return a+b
print(add()) #沒傳參數就使用預設參數
print(add(3,5))
3
8
3.5.2 類別和方法
#class A(object): 所有類別預設繼承 object,所以不宣告也可以
class A():
#方法第一個參數必須存在,一般習慣命名 self,呼叫方法時不需為這參數傳值
def add(self,a,b):
return a+b
cnt=A()
print(cnt.add(3,5))
class A():
#建立類別時首先宣告初始化的方法 _ _init_ _
def __init__(self,a,b):
self.a=int(a)
self.b=int(b)
def add(self):
return self.a+self.b
cnt=A('4',5)
print(cnt.add())
9
class A():
def add(self,a,b):
return a+b
class B(A): #B類別繼承A類別
def sub(self,a,b):
return a-b
print(B().add(3,5))
8
-------------------------------------- 3.6 模組
3.6.1 參考模組
>>> import time
>>> help(time)
Help on built-in module time:
.
.
.
>>> print(time.ctime())
Fri Jan 24 08:51:44 2020
>>> from time import ctime
>>> print(ctime())
Fri Jan 24 08:53:48 2020
from time import *
print(ctime())
print("休眠2秒")
sleep(2)
print(ctime())
Fri Jan 24 08:57:56 2020
休眠2秒
Fri Jan 24 08:57:58 2020
3.6.2 模組呼叫
# project/pub.py
def add(a,b):
return a+b
# project/count.py
from pub import add
print(add(4,5))
9
# 在 project/ 下多了一個檔案 __pycache__/pub.cpython-38.pyc 預先編譯的模組,為了加強模組載入速度
3.6.3 跨目錄模組呼叫
# project/model/pub.py
def add(a,b):
return a+b
# project/count.py
from model.pub import add
print(add(4,5))
9
3.6.4 進一步討論跨目錄模組呼叫
# \project\model\count.py
class A():
def add(self,a,b):
return a+b
# \project\model\new_count.py
from .count import A
class B(A):
def sub(self,a,b):
return a-b
resule=B().add(2,5)
print(resule)
# \project\test.py
import sys
sys.path.append("./model")
from model import new_count
test=new_count.B()
test.add(2,5)
7
3.7.1 認識例外
Python 用例外物件 exception object 來表示例外情況 ,遇到錯誤後會引發例外。如果例外物件並未處理或捕捉,則程式就會用回溯 Traceback 來終止執行。
>>> open("abc.txt",'r')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open("abc.txt",'r')
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
# 透過 open() 方法,以讀 'r' 的方式開啟不存在的檔案
try:
open("abc.txt",'r')
except FileNotFoundError:
print("例外了!")
例外了!
>>> print(aa)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print(aa)
NameError: name 'aa' is not defined
try:
open(aa)
except NameError:
print("例外了!")
例外了!
在 Python 中所有的例外類別都繼承 BaseException,所以可使用它來接收所有類型例外
try:
open(aa)
except BaseException:
print("例外了!")
例外了!
# 告訴我們例外的原因
try:
print(aa)
except BaseException as msg:
print(msg)
name 'aa' is not defined
3.7.2 更多例外用法
try:
print(aa)
except BaseException as msg:
print(msg)
else:
print("沒有例外!")
name 'aa' is not defined
try:
aa="例外測試"
print(aa)
except BaseException as msg:
print(msg)
else:
print("沒有例外!")
例外測試
沒有例外!
try:
aa="例外測試"
print(aa)
except BaseException as msg:
print(msg)
else:
print("沒有例外!")
finally:
print("不管是否例外,都會被執行。")
例外測試
沒有例外!
不管是否例外,都會被執行。
3.7.3 拋出例外
from random import randint
N=randint(1,9)
if N%2==0:
raise BaseException("%d is even" %N)
else:
raise BaseException("%d is odd" %N)
Traceback (most recent call last):
File "C:/Users/kk/Desktop/0.py", line 4, in <module>
raise BaseException("%d is even" %N)
BaseException: 8 is even
N=randint(1,9)
if N%2==0:
raise BaseException("%d is even" %N)
else:
raise BaseException("%d is odd" %N)
Traceback (most recent call last):
File "C:/Users/kk/Desktop/0.py", line 4, in <module>
raise BaseException("%d is even" %N)
BaseException: 8 is even
CH12 程式邏輯發展練習(45-50)
(45).開檔讀檔寫檔 (循序檔)
c1="";print(c1)
with open("ipfile_1.txt",'r',encoding='utf-8') as file_1:
for c1 in file_1:
print(c1)
with open("ipfile_2.txt",'r',encoding='utf-8') as file_2:
c2=file_2.read()
t="Hello "+c1+c2
with open (c1.strip()+".txt",'w',encoding='utf-8') as new_file:
new_file.write(t)
print("檔案順利建立並寫入!")
file_1.close()
file_2.close()
aa
檔案順利建立並寫入!
ipfile_1.txt 內容:aa
ipfile_2.txt 內容: only for English!
建立檔案 aa.txt 內容:Hello aa only for English!
--------
with open("ipfile_1.txt",'r',encoding='utf-8') as file_1:
c1=file_1.read()
for i in range(len(c1)+1):
print(c1[i:i+1],end=' ')
print()
file_1.close()
a a
--------
with open("ipfile_1.txt",'r',encoding='utf-8') as file_1:
c1=file_1.read()
for i in range(len(c1)+1):
print(c1[i:i+1],end='')
print()
file_1.close()
with open("ipfile_1.txt",'r',encoding='utf-8') as file_1:
for i in range(0,len(c1)+1):
a=file_1.read(i)
print(a,end='')
print()
file_1.close()
fp=open('factorial.txt','r')
line=fp.readline()
while line:
print(line,end='')
line=fp.readline()
fp.close()
aabbcc
aabbcc
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
(46).找圖檔解析度
(47).檔案雜湊演算法(哈希表)
import hashlib
def hash_file(file_name):
h=hashlib.sha1()
with open(file_name,'rb') as file:
chunk=0;n=0
while chunk != b'':
chunk=file.read(1024)
h.update(chunk)
n=n+1
print("檔案長度=",n-1,'k')
print("檔案結束碼=",chunk)
return h.hexdigest()
message= hash_file("aa.txt")
print(message)
檔案長度= 0 k
檔案結束碼= b'zxcvbnm'
檔案長度= 1 k
檔案結束碼= b''
93ec71b22793a81569c94ca17e4d9c293d8e201f
常見的 Hash 演算法: Message Digest Algorithm MD2,MD4,MD5,Secure Hash Algorithm SHA1,SHA256,SHA512
(48).文字字串轉數字串列
ipline='3 27 1586 93 688'
ipline=' '+ipline+' '
print(ipline)
numlist=[]
strlen=len(ipline)
c=0;l=0;r=0
for i in range(strlen):
if ipline[i]==' ':
l=r;r=i
c=c+1
if c>1:
numlist.append(int(ipline[l+1:r]))
print(numlist)
3 27 1586 93 688
[3, 27, 1586, 93, 688]
-------- 文字字串轉數字串列
ipline="1 10 100 1000 10000"
print(ipline)
def myMap(ipline):
ipline=' '+ipline+' '
strlen=len(ipline);
L=0;R=0;c=0;numlist=[]
for i in range(strlen):
print(ipline[i],end='')
if ipline[i]==' ':
print(i,end='')
L=R;R=i;print(L,R)
c=c+1;print(c)
if c>1:
numlist.append(int(ipline[L+1:R]))
return numlist
listA=myMap(ipline)
print(listA)
00 0
1
1 2 0 2
2
10 5 2 5
3
100 9 5 9
4
1000 14 9 14
5
10000 20 14 20
6
[1, 10, 100, 1000, 10000]
1 10 100 1000 10000
012345678901234567890
-------- 字串 串列 互轉
ipline="1 10 100 1000 10000"
print(ipline)
def Convert(string):
list1=list(string.split(" "))
return list1
numlist=Convert(ipline)
print(numlist)
1 10 100 1000 10000
['1', '10', '100', '1000', '10000']
-------- 字串轉陣列 再轉字串
n=5
ipline='1 10 100 1000 10000'
print(n)
newlist=ipline.split(' ')
print(newlist)
newstr=' '.join(newlist)
print(newstr)
5
['1', '10', '100', '1000', '10000']
1 10 100 1000 10000
------- 字串變成整數串列
ipline='3 27 1586 93 688'
list=ipline.split(' ')
print(list)
w=[int(x) for x in list]
print(w)
['3', '27', '1586', '93', '688']
[3, 27, 1586, 93, 688]
1. 文字字串 轉成 數值串列 list01=list(map(int,data.split()))
2. 文字字串 轉成 文字串列 datalist02=datastring.split(' ')
3. 數值串列 轉成 文字字串 print(datalist01[i],end='')
4. 文字串列 轉成 文字字串 print(str(datalist01[i]),end='')
5. 字串前後去除空白 print(strline.strip())
(49).陣列反轉0
#n=int(input())
#ipline=input()
n=5
ipline="2 3 12 4 5"
ipline=' '+ipline+' '
numlist=[]
strlen=len(ipline)
c=0;k=0;L=0;R=0
for i in range(strlen):
if ipline[i]==' ':
L=k;R=i
k=R
c=c+1
if c>1:
numlist.append(int(ipline[L+1:R]))
numlist.reverse()
c=len(numlist)
re=' '
for i in range(c):
if i<c-1:
re=re+str(numlist[i])+' '
else:
re=re+str(numlist[i])
print(re)
5 4 12 3 2
---------------- 陣列反轉1
n=5
ipline="2 3 12 4 5"
a=ipline.split(' ')
print(a)
print(' '.join(reversed(a)))
['2', '3', '12', '4', '5']
5 4 12 3 2
---------------- 陣列反轉2
n=5
ipline="2 3 12 4 5"
a=map(int,ipline.split(' '))
print(' '.join(map(str,reversed(list(a)))))
5 4 12 3 2
---------------- 陣列反轉3
n=5
ipline="2 3 12 4 5"
lista=list(map(int,ipline.split(' ')))
lista.reverse()
print(' '.join(map(str,lista)))
5 4 12 3 2
---------------- 整理 使用過的函數
#數值串列反轉
list=[2,3,12,4,5]
list.reverse()
print(list)
[5, 4, 12, 3, 2]
#字串 空白分割字串
ipline="2 3 12 4 5"
a=ipline.split(' ')
print(a)
['2', '3', '12', '4', '5']
#
ipline="2 3 12 4 5"
a=map(int,ipline.split(' ')) #數值串列,但不能印出
print(' '.join(map(str,reversed(list(a)))))
5 4 12 3 2
#
ipline="2 3 12 4 5"
lista=list(map(int,ipline.split(' ')))
lista.reverse()
print(lista)
[5, 4, 12, 3, 2]
(50). 統計每個字串的字元數量
#離線解題
n=5
iplist=["0","00","5140514","9999999999","1234567890"]
for i in range(n):
print(iplist[i],end=' ')
for j in range(10):
c=iplist[i].count(str(j))
print(c,end=' ')
c=0
print()
0 1 0 0 0 0 0 0 0 0 0
00 2 0 0 0 0 0 0 0 0 0
5140514 1 2 0 0 2 2 0 0 0 0
9999999999 0 0 0 0 0 0 0 0 0 10
1234567890 1 1 1 1 1 1 1 1 1 1
n=int(input())
for i in range(n):
ipline=input()
print(ipline,end=' ')
for j in range(10):
c=ipline.count(str(j))
print(c,end=' ')
print()
0
0 1 0 0 0 0 0 0 0 0 0
00
00 2 0 0 0 0 0 0 0 0 0
5140514
5140514 1 2 0 0 2 2 0 0 0 0
9999999999
9999999999 0 0 0 0 0 0 0 0 0 10
1234567890
1234567890 1 1 1 1 1 1 1 1 1 1
訂閱:
文章 (Atom)