--- title: Python note2 tags: Python description: View the slide with "Slide Mode". --- # **Python 筆記** :::danger ### 裡面可能包含大量bug,請斟酌服用!!! ::: ## 部分內容會與C++進行對比 --- # 大綱 :::spoiler 展開 [TOC] ::: --- # 變數宣告 ## 一個變數,必須知道 * ### 身份 * ### 名字 * ### 值域 ## 身份 * ### 整數 * ### 浮點數 * ### 字元 * ### 字串 * ### 布林 ## 名字 * ### 第ㄧ個字母不可為數字 * ### 變數不得有空白 * ### 變數名稱不得與保留字相同 * ### 符號只能使用_ ## 值域 * ### 除了 ```def():``` 內的東西為獨立外,都為共享 ## 特點 * ### 不需要先宣告身份 #### python ```python= a = 1 #a為整數,且值為1 b = 1.22 #b為浮點數,且值為1.22 c = "Vincenttainan" #c為字串,且值為"Vincenttainan" ``` #### C++ ```cpp= int a = 1; //a為整數,且值為1 double b = 1.22; //b為浮點數,且值為1.22 string c = "Vincenttainan"; //c為字串,且值為"Vincenttainan" ``` * ### 可同一列指派不同的值 #### python ```python= a , b , c = 1 , 1.22 , "Vincenttainan" #a為整數,且值為1 #b為浮點數,且值為1.22 #c為字串,且值為"Vincenttainan" ``` #### C++ ```cpp= int a ; double b ; string c ; a = 1; b = 1.22; c = "Vincenttainan"; //a為整數,且值為1 //b為浮點數,且值為1.22 //c為字串,且值為"Vincenttainan" ``` * ### 強制轉換 #### python ```python= a = "12384" b = int(a) #b為整數,且值為12384 ``` #### C++ ```cpp= string a = "12384" ; int b = 0 ; for( int i = 0 ; i < a.size() ; i++ ){ if( a[i] == '0' ){ //code } else if( //code ){ //code } //code //一番激烈的運算 } //b為整數,且值為12384 ``` --- # 基本語法 ## 一些簡單的語法 * ### 輸出 * ### 輸入 * ### 條件 * ### for迴圈 * ### while迴圈 ## 輸出 ### 程式碼 ```python print( 物件A , 物件B , ... , sep="X" , end="Y" ) ``` 輸出 物件A 物件B ... 並以 X 作為間隔 最後輸出 Y sep , end 可以不填 預設 sep 為 " " 預設 end 為 "\n" | Python | C++ | | -------- | -------- | |```print(A,B,C)```|```cout<<A<<" "<<B<<" "<<C<<"\n";```| ### 範例 #### 輸出單一物件 ##### python= ```python print( "Vincenttainan" ) ``` ##### C++ ```cpp= cout<<"Vincenttainan"<<endl; ``` ##### output ``` Vincenttainan ``` #### 輸出多種物件 ##### python= ```python= a="Vincent" b="tainan" print( a , b ) ``` ##### C++ ```cpp= string a="Vincent"; string b="tainan"; cout<<a<<" "<<b<<endl; ``` ##### output ``` Vincent tainan ``` #### 更改間隔 ##### python ```python= a="Vincent" b="tainan" c="notorz" print( a , b , c , sep=" ! " ) ``` ##### C++ ```cpp= string a="Vincent"; string b="tainan"; string c="notorz"; cout<<a<<" ! "<<b<<" ! "<<c<<endl; ``` ##### output ``` Vincent ! tainan ! notorz ``` #### 更改換行 ##### python ```python= a="Vincent" b="tainan" print( a , b , end=" orz\n" ) ``` ##### C++ ```cpp= string a="Vincent"; string b="tainan"; cout<<a<<" "<<b<<"orz"<<" orz\n"; ``` ##### output ``` Vincent tainan orz ``` #### 更改間隔、換行 ##### python ```python= a="Vincent" b="tainan" c="notorz" print( a , b , c , sep=" ! " , end=" orz\n" ) ``` ##### C++ ```cpp= string a="Vincent"; string b="tainan"; string c="notorz"; cout<<a<<" ! "<<b<<" ! "<<c<<"orz\n"; ``` ##### output ``` Vincent ! tainan ! notorz orz ``` ## 輸入 ### 程式碼 ```python input() ``` 讀入一的值,並儲存為字串 ```python .split( "text" ) ``` 以 "text" 為基準,把輸入的值拆成部份 預設為" " | Python | C++ | | -------- | -------- | |```A=input()```|```cin>>A;```| ### 範例 #### 輸入只有一行字串 ##### input ``` Vincent tainan ``` ##### python ```python= A=input() ``` ##### C++ ```cpp= string A; getline(cin,A); ``` #### 輸入有兩行字串 ##### input ``` Vincent tainan YYouo orz ``` ##### python ```python= A=input() B=input() ``` ##### C++ ```cpp= string A,B; getline(cin,A); getline(cin,B); ``` #### 輸入有一行,只有一個數字 ##### input ``` 48763 ``` ##### python ```python= A=int(input()) ``` ##### C++ ```cpp= int A; cin>>A; ``` #### 輸入有一行,只有兩個數字 ##### input ``` 48763 54877 ``` ##### python ```python= A,B=map(int,input().split()) ``` ##### C++ ```cpp= int A,B; cin>>A>>B; ``` #### 輸入有一行,只有一個數字、一個字串 ##### input ``` 48763 Vincenttainan ``` ##### python ```python= A,B=map(str,input().split()) A=int(A) ``` ##### C++ ```cpp= string A; int B; cin>>A>>B; ``` ## 條件 ### 程式碼 ```python if condition1: #code1 elif condition2: #code2 else: #code3 ``` 判斷條件 condition1 是否正確 若正確,便執行 code1 否則判斷條件 condition2 是否正確 若正確,便執行 code2 否則便執行 code3 | Python | C++ | | -------- | -------- | |```if a%2==0:```|```if(a%2==0){```| |``` print("02468")```|``` cout<<"02468"<<endl;```| ||```}```| ### 範例 #### 判斷大小 ##### input ``` 10 15 ``` ##### python= ```python A=int(input()) B=int(input()) if A>B: print(A) else: print(B) ``` ##### C++ ```cpp= int A,B; cin>>A>>B; if(A>B){ cout<<A<<endl; } else{ cout<<B<<endl; } ``` ##### output ``` 15 ``` ## for迴圈 ### 程式碼 ```python for i in range( A , B , C ): ``` 開一個變數i,從 i=A 開始,每次加 C ,直到值超過 B | Python | C++ | | -------- | -------- | |```for i in range( A , B , C ):```|```for( int i=A ; i<B ; i+=C ){}```| ### 範例 #### 從 0 開始,輸出到 A-1 ,每次加 1 ##### input ``` 5 ``` ##### python ```python A = int(input()) for i in range( 0 , A , 1 ): print( i ) ``` ##### C++ ```cpp int A; cin>>A; for( int i=0 ; i<A ; i++ ){ cout<<A<<endl; } ``` ##### output ``` 0 1 2 3 4 ``` ## while迴圈 ### 程式碼 ```python while condition: ``` 每次判斷 condition 是否為真 若為真,變執行 否則,離開迴圈 | Python | C++ | | -------- | -------- | |```while condition:```|```while(condition){}```| ### 範例 #### 從 0 開始,輸出到 A-1 ,每次加 1 ##### input ``` 5 ``` ##### python ```python A = int(input()) i=0 while i<A: print( i ) i+=1 ``` ##### C++ ```cpp int A; cin>>A; int i=0; while( i<A ){ cout<<i<<endl; i+=1; } ``` ##### output ``` 0 1 2 3 4 ``` --- # 資料結構 ## 一些簡單的結構 * 字串 * 列表 * 元組 * 字典 * 集合 ## 字串 ### 格式 使用""或''包起來 ```python s="Vincenttainan" ``` | indx左至右 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |-------- | -------- | | string| V | i | n | c | e | n | t | t | a | i | n | a | n | | indx右至左 | -13 | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 | ### 運算子 #### 一些常用的字串運算 * 字串連接 * 字串重複 * 索引數值所在字元 * 截取部分字串 * 查詢是否在內 #### 字串連接 語法 : ```string1 + string2``` 翻譯 : ```把 string2 接到 string1 後面``` 範例 ##### python ```python= a="Vincent" b="tainan" c=a+b print(c) ``` ##### C++ ```cpp= string a="Vincent"; string b="tainan"; string c=a+b; cout<<c<<endl; ``` ##### output ``` Vincenttainan ``` #### 字串重複 語法 : ```string * int ``` 翻譯 : ```把前字串重複 int 次``` 範例 ##### python ```python= a="Vincent" b=a*2 print(b) ``` ##### C++ ```cpp= string a="Vincent"; string c; int b=2; for(int i=0;i<b;i++){ c+=a; } cout<<c<<endl; ``` ##### output ``` VincentVincent ``` #### 索引數值所在字元 語法 : ```string[indx]``` 翻譯 : ```查詢字串第indx的值``` 範例 ##### python ```python= a="Vincent" b=a[0] print(b) b=a[4] print(b) ``` ##### C++ ```cpp= string a="Vincent"; char b; b=a[0]; cout<<b<<endl; b=a[4]; cout<<b<<endl; ``` ##### output ``` V e ``` #### 截取部分字串 語法 : ```string[ start : end : step ]``` 翻譯 : ```indx 從 strat 開始,每次加 step , 直到超過 end 結束``` 範例 ##### python ```python= a="Vincent" b=a[0:3:1] print(b) b=a[::-1] print(b) ``` ##### C++ ```cpp= string a="Vincent"; for(int i=0;i<3;i+=1){ cout<<a[i]; } cout<<endl; for(int i=6;i>=0;i+=-1){ cout<<a[i]; } cout<<endl; ``` ##### output ``` Vin tnecniV ``` #### 查詢是否在內 語法 : ```string1 in string2``` 翻譯 : ```查詢 string2 是否在 string1 中``` 範例 ##### python ```python= a="Vincent" b="Vin" ans = b in a print(ans) b="XXX" ans = b in a print(ans) ``` ##### C++ ```cpp= //暴力解 or KMP演算法 ``` ##### output ``` True False ``` ### 函數 #### 一些常用的字串函數 * len() * .upper() * .lower() * .isupper() * .islower() * .find() * .replace() #### len() 語法 : ```len(string)``` 翻譯 : ```回傳 string 的長度``` 範例 ##### python ```python= s="Vincenttainan" n=len(s) print(n) ``` ##### C++ ```cpp= string s="Vincenttainan"; int n=s.size(); cout<<n<<endl; ``` ##### output ``` 13 ``` #### .upper() 語法 : ```string.upper()``` 翻譯 : ```將 string 轉為大寫``` 範例 ##### python ```python= s="Vincenttainan" s2=s.upper() print(s) ``` ##### C++ ```cpp= string s="Vincenttainan"; for(int i=0;i<s.size();i++){ if(s[i]>='a'&&s[i]<='z'){ s[i]+=('A'-'a'); } } cout<<s<<endl; ``` ##### output ``` VINCENTTAINAN ``` #### .lower() 語法 : ```string.lower()``` 翻譯 : ```將 string 轉為小寫``` 範例 ##### python ```python= s="VINCENTTAINAN" s2=s.lower() print(s) ``` ##### C++ ```cpp= string s="VINCENTTAINAN"; for(int i=0;i<s.size();i++){ if(s[i]>='A'&&s[i]<='Z'){ s[i]+=('a'-'A'); } } cout<<s<<endl; ``` ##### output ``` vincenttainan ``` #### .isupper() 語法 : ```string.isupper()``` 翻譯 : ```回傳 string 是否都為大寫``` 範例 ##### python ```python= s="Vincenttainan" b=s.isupper() print(b) s="VINCENTTAINAN" b=s.isupper() print(b) ``` ##### C++ ```cpp= string s="Vincenttainan"; bool flag=0; for(int i=0;i<s.size();i++){ if(!(s[i]>='A'&&s[i]<='Z')){ flag=1; break; } } if(flag==0) cout<<"True"<<endl; else cout<<"Flase"<<endl; s="VINCENTTAINAN"; flag=0; for(int i=0;i<s.size();i++){ if(!(s[i]>='A'&&s[i]<='Z')){ flag=1; break; } } if(flag==0) cout<<"True"<<endl; else cout<<"Flase"<<endl; ``` ##### output ``` Flase True ``` #### .islower() 語法 : ```string.islower()``` 翻譯 : ```回傳 string 是否都為小寫``` 範例 ##### python ```python= s="Vincenttainan" b=s.islower() print(b) s="vincenttainan" b=s.islower() print(b) ``` ##### C++ ```cpp= string s="Vincenttainan"; bool flag=0; for(int i=0;i<s.size();i++){ if(!(s[i]>='a'&&s[i]<='z')){ flag=1; break; } } if(flag==0) cout<<"True"<<endl; else cout<<"Flase"<<endl; s="vincenttainan"; flag=0; for(int i=0;i<s.size();i++){ if(!(s[i]>='a'&&s[i]<='z')){ flag=1; break; } } if(flag==0) cout<<"True"<<endl; else cout<<"Flase"<<endl; ``` ##### output ``` Flase True ``` #### .find() 語法 : ```string.find( string2 )``` 翻譯 : ```回傳 string 中 string2 開頭的位置``` ```若沒有則回傳-1``` 範例 ##### python ```python= s="Vincenttainan" s2="cent" n=s.find(s2) print(n) ``` ##### C++ ```cpp= string s="Vincenttainan"; string s2="cent"; int n=s.find(s2); cout<<n<<endl; ``` ##### output ``` 3 ``` #### .replace() 語法 : ```string.replace( string2 , string3 , int )``` 翻譯 : ```將 string 中 string2 取代為 strin3 ,最多做 int 次``` ``` int 不填則無上限 ``` 範例 ##### python ```python= s="Vincenttainan" s2="nan" s3="isnotorz" s4=s.replace( s2,s3 ) print(s4) ``` ##### C++ ```cpp= string s="Vincenttainan"; string s2="nan"; string s3="isnotorz"; int indx=0; while(true){ indx=s.find(s2,indx); if(indx==-1) break; else{ s.replace(indx, s2.size(), s3); } indx+=s3.size(); } cout<<s<<endl; ``` ##### output ``` Vincenttaiisnotorz ``` ## 列表 ### 格式 使用[ ]包起來的 ```python arr = [ "Vincent" , "Tainan" , 999 ] ``` | indx由左至右 | 0 | 1 | 2 | | -------- | -------- | -------- | -------- | | 內容 | "Vincent" | "Tainan" | 999 | ### 運算子 #### 一些常用的運算子 * 列表串接 * 列表重複 * 截取索引值所在列表元素 * 截取部分列表 #### 列表串連 語法 : ```list1 + list2``` 翻譯 : ```把 list2 接到 list1 後面``` 範例 ##### python ```python= a=["Vincent","tainan"] b=[100,200] c=a+b print(c) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` ['Vincent', 'tainan', 100, 200] ``` #### 列表重複 語法 : ```list1 * int ``` 翻譯 : ```把 list1 重複 int 次``` 範例 ##### python ```python= a=["Vincent","tainan"] b=a*2 print(b) ``` ##### C++ ```cpp= string s[10]={"Vincent","tainan"}; for(int i=0;i<2;i++){ s[i+2]=s[i]; } cout<<"['"<<s[0]<<"', "<<s[1]<<"', "<<s[2]<<"', "<<s[3]<<"']"<<endl; ``` ##### output ``` ['Vincent', 'tainan', 'Vincent', 'tainan'] ``` #### 截取索引值所在列表元素 語法 : ```list1[indx] ``` 翻譯 : ```調取 list1 的第 indx 個值``` 範例 ##### python ```python= a=["Vincent","tainan",999] b=a[1] print(b) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` tainan ``` #### 截取部分列表 語法 : ```list[ start : end : step ]``` 翻譯 : ```indx 從 strat 開始,每次加 step , 直到超過 end 結束``` 範例 ##### python ```python= a=["Vincent","tainan",999,1024] b=a[0:3:1] print(b) b=a[::-1] print(b) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` ['Vincent', 'tainan', 999] [1024, 999, 'tainan', 'Vincent'] ``` ### 函數 #### 一些常用的函數 * len() * list() * .clear() * .append() * .extend() * .remove() * .reverse() #### len() 語法 : ```len(list)``` 翻譯 : ```回傳 list 的大小``` 範例 ##### python ```python= l=["Vincent",999,"tainan"] n=len(l) print(n) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` 3 ``` #### list() 語法 : ```list(string)``` 翻譯 : ```將 string 猜成 list 型態``` 範例 ##### python ```python= s="Vincenttainan" l=list(s) print(l) ``` ##### C++ ```cpp= string s="Vincenttainan"; char l[15]; for(int i=0;i<s.size();i++){ l[i]=s[i]; } cout<<"['"<<l[0]; for(int i=1;i<s.size();i++){ cout<<"', '"<<s[i]; } cout<<"']"<<endl; ``` ##### output ``` ['V', 'i', 'n', 'c', 'e', 'n', 't', 't', 'a', 'i', 'n', 'a', 'n'] ``` #### .clear() 語法 : ```list.clear()``` 翻譯 : ```刪除 list 裡面的所有東西``` 範例 ##### python ```python= l=["Vincent",999,"tainan"] print(l) l.clear() print(l) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` ['Vincent', 999, 'tainan'] [] ``` #### .append() 語法 : ```list.append(thing)``` 翻譯 : ```把 thing 植入 list 的最尾端``` 範例 ##### python ```python= l=["Vincent","tainan"] print(l) l.append(999) print(l) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` ['Vincent', 'tainan'] ['Vincent', 'tainan', 999] ``` #### .extend() 語法 : ```list1.extend(list2)``` 翻譯 : ```把 list2 內的值植入 list1 的最尾端``` 範例 ##### python ```python= l=["Vincent","tainan"] l2=[999,666] l.append(l2) print(l) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` ['Vincent', 'tainan', 999, 666] ``` #### .remove() 語法 : ```list.remove(thing)``` 翻譯 : ```把 list 內的 thing 移除``` 範例 ##### python ```python= l=["Vincent","tainan",999,666] l.remove(999) print(l) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` ['Vincent', 'tainan', 666] ``` #### .reverse() 語法 : ```list.reverse``` 翻譯 : ```把 list 頭尾翻轉``` 範例 ##### python ```python= l=["Vincent","tainan",999,666] l.reverse() print(l) ``` ##### C++ ```cpp= // C++ 的陣列只能存一種元素 ``` ##### output ``` [666, 999, 'tainan', 'Vincent'] ``` ## 元組 ### 格式 使用()包起來的 ```python tup=("Vincent",[999,666],"tainan") ``` | indx由左至右 | 0 | 1 | 2 | | -------- | -------- | -------- | -------- | | 內容 | "Vincent" | [999,666] | "tainan" | 元組的內容不可修改 基本上只能使用:截取索引值所在列表元素 ## 字典 ### 格式 使用{}包起來的,每組有兩個物件 a:b ```python dic={ "Vincent":666 , "Tainan":999 } ``` | indx | "Vincnet" | "Tainan" | | -------- | -------- | -------- | | 內容 | 666 | 999 | 字典由右值 key ,取左值 value ### 運算子 #### 一些常用的運算子 * 字典取值 * 字典新增 * 字典修改 * 字典刪除鍵值 * 字典刪除 #### 字典取值 spoiler 語法:```dic[ 元素 ] ``` 翻譯 : ```尋找 dic 內 元素 的值``` 範例 ##### python ```python= dic={ "Vincent":666 , "Tainan":999 } n=dic["Vincent"] print(n) ``` ##### C++ ```cpp= map<string, intdic; dic["Vincent"]=666; dic["Tainan"]=999; cout<<dic["Vincent"]<<endl; ``` ##### output ``` 666 ``` #### 字典新增 spoiler 語法:```dic[ 元素1 ] = 元素2 ``` 翻譯 : ```在 dic 內增加以 元素1 對應 元素2 的組合``` 範例 ##### python ```python= dic={ "Vincent":666 , "Tainan":999 } dic["orz"]=0 print(dic["orz"]) ``` ##### C++ ```cpp= map<string, intdic; dic["Vincent"]=666; dic["Tainan"]=999; dic["orz"]=0; cout<<dic["orz"]<<endl; ``` ##### output ``` 0 ``` #### 字典修改 spoiler 語法:```dic[ 已在元素 ] = 元素2 ``` 翻譯 : ```將 dic 內增 已在元素 對應值改為 元素2``` 範例 ##### python ```python= dic={ "Vincent":666 , "Tainan":999 } dic["Vincent"]=999 print(dic["Vincent"]) ``` ##### C++ ```cpp= map<string, intdic; dic["Vincent"]=666; dic["Tainan"]=999; dic["Vincent"]=999; cout<<dic["Vincent"]<<endl; ``` ##### output ``` 0 ``` #### 字典刪除鍵值 spoiler 語法:```del dic[ 已在元素 ]``` 翻譯 : ```將 dic 內增 已在元素 刪除``` 範例 ##### python ```python= dic={ "Vincent":666 , "Tainan":999 } del dic["Vincent"] print(dic) ``` ##### C++ ```cpp= map<string, intdic; dic["Vincent"]=666; dic["Tainan"]=999; dic.erase("Vincent") //遍歷 dic 並輸出 ``` ##### output ``` {'Tainan': 999} ``` #### 字典刪除 spoiler 語法:```del dic``` 翻譯 : ```將 dic 刪除``` 範例 ##### python ```python= dic={ "Vincent":666 , "Tainan":999 } del dic ``` ##### C++ ```cpp= map<string, intdic; dic["Vincent"]=666; dic["Tainan"]=999; dic.empty(); ``` ## 集合 ### 格式 使用{}包起來的 ```python st={ 'a' , 'b' , 'c' } ``` 集合中,物件以無序排列 每種元素只會存在一個 ### 運算子 #### 一些常用的運算子 * 連集 * 交集 * 差集 * 斥集 #### 連集 spoiler 語法:```seta | setb``` 翻譯 : ```seta 和 setb 內所有的值``` 範例 ##### python ```python= st1={1,3,4,5,7} st2={2,4,6,7,8} st3=st1|st2 print(st3) ``` ##### output ``` {1, 2, 3, 4, 5, 6, 7, 8} ``` ##### C++ ```cpp= set<int> st1={1,3,4,5,7}; set<int> st2={2,4,6,7,8}; set<int> st3; for(const auto &s:st1){ st3.insert(s); } for(const auto &s:st2){ st3.insert(s); } for(const auto &s:st3){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` 1 2 3 4 5 6 7 8 ``` #### 交集 spoiler 語法:```seta & setb``` 翻譯 : ```僅 seta 或 setb 同時有的值``` 範例 ##### python ```python= st1={1,3,4,5,7} st2={2,4,6,7,8} st3=st1&st2 print(st3) ``` ##### output ``` {4, 7} ``` ##### C++ ```cpp= set<int> st1={1,3,4,5,7}; set<int> st2={2,4,6,7,8}; set<int> st3; for(const auto &s:st1){ if(st2.count(s)){ st3.insert(s); } } for(const auto &s:st3){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` 4 7 ``` #### 差集 spoiler 語法:```seta - setb``` 翻譯 : ```seta 減去 setb 內的值``` 範例 ##### python ```python= st1={1,3,4,5,7} st2={2,4,6,7,8} st3=st1-st2 print(st3) st3=st2-st1 print(st3) ``` ##### output ``` {1, 3, 5} {8, 2, 6} ``` ##### C++ ```cpp= set<int> st1={1,3,4,5,7}; set<int> st2={2,4,6,7,8}; set<int> st3; for(const auto &s:st1){ st3.insert(s); } for(const auto &s:st2){ st3.erase(s); } for(const auto &s:st3){ cout<<s<<" "; } cout<<endl; for(const auto &s:st2){ st3.insert(s); } for(const auto &s:st1){ st3.erase(s); } for(const auto &s:st3){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` 1 3 5 2 6 8 ``` #### 斥集 spoiler 語法:```seta ^ setb``` 翻譯 : ```seta 和 setb 內所有的值減去 seta 和 setb 同時有的值``` 範例 ##### python ```python= st1={1,3,4,5,7} st2={2,4,6,7,8} st3=st1^st2 print(st3) ``` ##### output ``` {1, 2, 3, 5, 6, 8} ``` ##### C++ ```cpp= set<int> st1={1,3,4,5,7}; set<int> st2={2,4,6,7,8}; set<int> st3; for(const auto &s:st1){ st3.insert(s); } for(const auto &s:st2){ st3.insert(s); } for(const auto &s:st1){ if(st2.count(s)){ st3.erase(s); } } for(const auto &s:st3){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` 1 2 3 5 6 8 ``` ### 函數 #### 一些常用的函數 * .add() * .remove() * set() #### .add() spoiler 語法:```set.add( object )``` 翻譯 : ```在 set 內加入 object 值``` 範例 ##### python ```python= st={1,2,3,4} st.add(5) print(st) ``` ##### output ``` {1, 2, 3, 4, 5} ``` ##### C++ ```cpp= set<int> st={1,2,3,4}; st.insert(5); for(const auto &s:st){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` 1 2 3 4 5 ``` #### .remove() spoiler 語法:```set.remove( object )``` 翻譯 : ```在 set 內移除 object 值``` 範例 ##### python ```python= st={1,2,3,4} st.remove(3) print(st) ``` ##### output ``` {1, 2, 4} ``` ##### C++ ```cpp= set<int> st={1,2,3,4}; st.erase(3); for(const auto &s:st){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` 1 2 4 ``` #### set() spoiler 語法:```set( object )``` 翻譯 : ```將 object 轉為 set 形式``` 範例 ##### python ```python= st=set("Vincenttainan") print(st) ``` ##### output ``` {'i', 'a', 't', 'V', 'e', 'n', 'c'} ``` ##### C++ ```cpp= string s="Vincenttainan"; set<char> st; for(int i=0;i<s.size();i++){ st.insert(s[i]); } for(const auto &s:st){ cout<<s<<" "; } cout<<endl; ``` ##### output ``` V a c e i n t ``` --- # 常用工具 ## 一些常用的工具 * def name(): * sort() ## def name(): ### 格式 ```python def name(input a,input b......): code code code return ``` 其中 input a 和 return 可填可不填 spoiler 比大小範例 輸入兩數值,回傳較大的數值 #### python ```python= def max(num1, num2): if num1>num2: return num1 return num2 ``` #### C++ ```cpp= int max(int num1,int num2){ if(num1>num2){ return num1; } return num2; } ``` spoiler 比較函數 for sort() 輸入兩數值,若前者較大,回傳True #### python ```python= def max(num1, num2): if num1>num2: return 1 return 0 ``` #### C++ ```cpp= int max(int num1,int num2){ if(num1>num2){ return 1; } return 0; } ``` ## sort() ### 格式 ```python sorted(arr,key=itemgetter(a,b,c...)) ``` ```python arr.sort(key=itemgetter(a,b,c...)) ``` 其中 key=itemgetter(a,b,c...) 可填可不填 但使用前要加上 ```python from operator import itemgetter, attrgetter ``` ### 正向排序 恩對,一維陣列的排序 #### python ```python= x=[4,2,5,3,1] y=sorted(x) print(y) ``` #### output ``` [1, 2, 3, 4, 5] ``` #### C++ ```cpp= int arr[10]={4,2,5,3,1}; sort(arr,arr+5); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } cout<<endl; ``` #### output ``` 1 2 3 4 5 ``` ### 反向排序 從大到小 #### python ```python= x=[4,2,5,3,1] y=sorted(x,reverse=True) print(y) ``` #### output ``` [5, 4, 3, 2, 1] ``` #### C++ ```cpp= int arr[10]={4,2,5,3,1}; sort(arr,arr+5,greater< int >()); for(int i=0;i<n;i++){ cout<<arr[i]<<" "; } cout<<endl; ``` #### output ``` 5 4 3 2 1 ``` ### 二維陣列 依第幾值排序 #### python ```python= scores = [ ('Jane', 'B', 12), ('John', 'A', 15), ('Dave', 'B', 11)] print(sorted(scores, key = lambda s: s[2])) ``` output ``` [('Dave', 'B', 11), ('Jane', 'B', 12), ('John', 'A', 15)] ``` #### C++ ```cpp= pair< pair< string,char >,int mp[5]; pair< pair< string,char >,int p; p.first.first="Jane"; p.first.second='B'; p.second=12; mp[0]=p; p.first.first="John"; p.first.second='A'; p.second=15; mp[1]=p; p.first.first="Dave"; p.first.second='B'; p.second=11; mp[2]=p; sort(mp,mp+3); p=mp[0]; cout<<p.first.first<<" "<<p.first.second<<" "<<p.second<<endl; p=mp[1]; cout<<p.first.first<<" "<<p.first.second<<" "<<p.second<<endl; p=mp[2]; cout<<p.first.first<<" "<<p.first.second<<" "<<p.second<<endl; ``` #### output ``` Dave A 11 Jane B 12 John A 15 ``` # 例題 ## 一中半島爭奪戰 ![](https://i.imgur.com/J15s6V8.png) ### 觀念 `輸入輸出` ### 翻譯 輸入兩整數 a,b ,輸出兩整數的差(加絕對值),如果為 0 則輸出 "all dead" ### 解法 :::spoiler 展開 ```python= a,b=map(int,input().split()) if a==b: print("all dead") else: print(abs(a-b)) ``` ::: --- ## 皇后 ![](https://i.imgur.com/u5JkSR0.png) ### 觀念 `數學(?` ### 翻譯 輸入四整數 x1,y1,x2,y2 ,判斷 (x1,y1),(x2,y2) 是否在同一個點、同一直線、同一斜線上 或者 在其他位置 ### 解法 :::spoiler 展開 ```python= x1,y1,x2,y2=map(int,input(),split()) if x1==x2 && y1==y2: print(0) elif x1==x2 or y1==y2: print(1) elif abs(x1-x2)==abs(y1-y2): print(1) else: print(2) ``` ::: --- ## 考試大樂透 ![](https://i.imgur.com/qjt10xR.png) ### 觀念 `多層迴圈` `爆搜` ### 翻譯 輸入兩整數陣列 a[9],b[9] (但其實只要用string存就可以了),判斷裡面有多少重複的號碼,一題目輸出 ### 解法 :::spoiler 展開 ```python= a=input().split() b=input().split() cnt=0 for i in range(0,9,1): for j in range(0,9,1): if a[i] == b[j]: cnt+=1 if cnt<5: print('I love TNFSH!') elif cnt==5: print(1000) elif cnt==6: print(10000) elif cnt==7: print(20000) elif cnt==8: print(100000) else: print('Only in your dreams!') ``` ::: --- ## 神奇遙控器 ![](https://i.imgur.com/7o212ZN.png) ### 觀念 `迴圈` ### 翻譯 輸入兩整數,依一定規則,迴圈或遞迴直到 a=b ### 解法 :::spoiler 展開 ```python= a,b=map(int,input().split()) cnt=0 while a!=b: if a%2==1: a-=1 else: a/=2 cnt+=1 print(cnt) ``` ::: --- ## 最大質因數 ![](https://i.imgur.com/Cb7lihK.png) ### 觀念 `自定義函數` `因數判斷` ### 翻譯 輸入一整數 n ,輸出 n 的最大質因數 ### 解法 :::spoiler 展開 ```python= def isP(X): for i in range(2,int(sqrt(X))+1,1): if X%i==0: return False return True n=int(input()) cnt=2 maxP=None while cnt<=n: if isP(cnt) and n%cnt==0: n/=cnt maxP=cnt cnt+=1 print(maxP) ``` ::: --- ## 小蘿莉的數學家教A ![](https://i.imgur.com/pd7UmgX.png) ### 觀念 `多層迴圈` `輸出內建函數` ### 翻譯 輸入兩整數 a,b ,輸出兩整數所代表的平行四邊形,並輸出底、高、面積 ### 解法 :::spoiler 展開 ```python= b,h=map(int,input().split()) for i in range(0,h,1): for j in range(0,h-i-1,1): print(" ",end="") for j in range(0,b,1): print("*",end="") print("") print("Base:",b) print("Height:",h) print("Area: ",b,"*",h,"=",b*h,sep="") ``` ::: --- ## yee~~~ ![](https://i.imgur.com/q3VR5CI.png) ### 觀念 `單層迴圈` `字串` `greedy(?` ### 翻譯 輸入一字串 S 依固定順序排序,問需要排序幾次 ### 解法 :::spoiler 展開 ```python= s=input() cnt=0 x=0 for i in range(0,len(s),1): if s[i]=="y": cnt+=abs(i-x) x+=3 print(cnt) ``` :::