---
tags: 教學, 教學3, AUV, python
---
:::info
https://hackmd.io/@NCTU-auv/S1haoPAiI
:::
[TOC]
# Python基礎
## Linux下的python
* 在終端機直接打`python`即可進入python2的互動模式,`python3`為python3的互動模式
* 若在```python```後面接檔名,會開始逐行執行該檔案
* 直接執行,在程式第一行加上```#!/usr/bin/env python```,並用```chmod```將檔案改成可執行檔。
---
## python基本變數型態
* int
* flaot
* str
```python=
a = 1
b = 1.
c = 0.1
d = '1'
```
```python=
a = 1
print(type(a))
b = float(a)
print(type(b))
c = str(a)
print(type(c))
d = int(c)
print(type(d))
```
---
## python 運算子
* 與C語言比較
|運算子| C | python |
| -------- | -------- | -------- |
| 加 | + | + |
| 減 | - | - |
| 乘 | * | * |
| 除 | / | / (//) |
| 取餘數 | % | % |
| 乘冪 | pow() | ** |
| 單行註解 | // | # |
* python2 : ```<int>/<int>```為整數除法,與C的結果相同
* python3 : ```<int>/<int>``` : 若無法整除,會自動轉乘float。若不想自動轉型,要用```<int>//<int>```
---
## 資料型別
### List
list 是一種 python特有的資料格式
用"type()"來查詢的話 會顯示:list
python中沒有陣列,只有list,不過list比C的array更強大,它可以自由改變長度,也可以容許在同一個list裡放不同型態的變數
#### list常見的function
* ```a=[]``` : 建立的list
* ```a=[1, 2, 3]``` : list初始化
* ```a[索引值]``` : list a成員讀取,索引值從0開始
* ```len(a)``` : 回傳list a的長度
* ```a.append(b)``` : 在a尾端加入成員b
* ```a.extend(B)``` : 在a尾端接收另一個list B
### Tuple
list 是一種 python特有的資料格式
用"type()"來查詢的話 會顯示:tuple
tuple跟list很像,唯一的差別是tuple內的資料無法更改。
#### list常見的function
* ```a=()``` : 建立的tuple
* ```a=(1, 2, 3)``` : tuple初始化
* ```a = (1,)``` : 只有單一成員tuple,初始化記得加```,```
* ```a[索引值]``` : tuple a成員讀取,索引值從0開始
### Dictionary
dictionary 是一種 python特有的資料格式
用"type()"來查詢的話 會顯示:dict
#### key 與 value

可以把 dictionary 的 key 想作是 list 的 index
在 ==Key== 的下面索引的的值 就是 ==value==
```python=
dict1 = {}
print(type(dict1))
#########
data = {
"name" : "Eason", #key 不可以是 list , 兩個索引之間以 "," 隔開
5:31,
"age" : 21,
"hobby" : ["basketball","videogames"],
"another_dict" : {"key1":"value"}
}
```
#### 添加修改與刪除 key
```python=
data["name"] = "Eric" #添加與修改
del data["name"] #刪除key
del dict1 #直接刪除整個dictionary
```
#### 當key不在dictionary內時
```python=
data.keys()
data.has_key("name") #python2.X 查詢key在不在dict裡面
data. __contains__("name") #python3.X 查詢key在不在dict裡面
data.has_key("car")
##############直接設立預設值#####################
print(data["girl friend"])
data.get("girl friend"," None ")
data.setdefault("girl friend","TW ice")
```
#### Dictionary 的宣告 - { }
| type | 符號 |
| -------- | -------- |
| tuple | ( ) |
| list | [ ] |
| dictionary | { } |
| set | { } |
#### Dictionary with Json
https://drive.google.com/file/d/11AgYNS6zUCh1n1yoiF6PSTtjz_ylaNA3/view
檔案內容
```
{
"Mass" : 35,
"Force_x" : 55,
"Force_y" : 26,
"Force_z" : 26,
"vel_x" : 8 ,
"vel_y" : 7 ,
"vel_z" : 2
}
```
```python=
import json
with open('super.json','r') as f:
data=json.load(f)
```
----
## range
* 產生一個整數的等差數列存
* 語法:range(start, stop, step)
* start:起始值(可省略,預設值為0)
* stop:中止值
* step:增值(可省略,預設值為1)
* 注意range範圍是**≧start, <stop**
* 檢視發法,轉成list
* Ex:t=range(0, 6, 2)
```a=list(t) #a=[0, 2, 4]```
---
## 判斷句
* `>`:大於
* `<`:小於
* `>=`:大於或等於
* `<=`:小於或等於
* `==`:等於(vs=:指派)
* `!=`:不等於
* `and`:且
* `or`:或
* `not`:非(真假對調)
* 這些在python裡也是可以用的
```python=
x=10
y=20
print(x is y)
print(x is not y)
print(x <= 5 and y <= 5)
print(x <= 5 or y <= 5)
print("C" in "Python")
print("C" in "C++")
```
* 範例
```python=
mood = "happy"
if mood is "happy":
print("^_^")
elif mood is "normal":
print("-_-")
elif mood is "sad":
print("Q_Q")
```
---
## 迴圈
### for迴圈
:::info
for <迭代變數> in <可迭代變數>:
<縮排><其他程式>
:::
* C
```C=
for(int i=0;i<10;i++){
printf("%d\n", i);
}
```
* python
```python=
for i in range(10):
print(i)
```
```python=
data=[]
for i in range(10):
data.append(i**2)
print(data)
```
* 列出1~a,是2或3的倍數但不是6的倍數的所有整數。
```python=
a=10
for i in range(1, a+1):
if i%2 == 0 or i%3 == 0:
if i%6 == 0:
pass
else:
print(i)
```
### while迴圈
:::info
while <判斷句>:
<縮排><其他程式>
:::
* C
```c=
int cnt = 10;
while(cnt--){
printf("%d\n", cnt);
}
```
* python
```python=
a = 10
while a > 0:
print(a)
a-=1
```
### 自定義函式
:::info
def <函數名稱>(<變數1>, <變數2>…):
<縮排><函數內容>
:::
* 範例
```python=
def f(x):
ans = 5*x**2-3*x-11
s = 5*x-3*x-11
return x, s
a = f(9)
print(a)
a, b = f(9)
print(a)
print(b)
```
* 應用,Cn取r,遞迴


```python=
def C(n, r):
if r == 0 or n == r:
ans = 1
else:
ans = C(n-1, r-1)+C(n-1, r)
return ans
s = C(4, 2)
print(s)
```
---
## Special Functions
### sort
* C++
```c=
#include<bits/stdc++.h>
using namespace std;
int a[5] = {1, 3, 4, 5, 2};
vector<int> num(a, a+sizeof(a)/sizeof(int));
sort(num.begin(), num.end());
```
* python
```python=
a = [1, 3, 4, 5, 2]
a = sorted(a)
```
## 把下面的C code改成python code
(UVA-12503: Robot Instructions)
```C++=
#include<stdio.h>
int main(){
int init = 1;
int time = 3;
char command[3] = {'L', 'R', 'S'};
int sc[3] = {0, 0, 2};
for (int l=0;l<init;l++){
int ans = 0;
int data[time];
for (int i=0;i<time;i++){
char s = command[i];
switch(s){
case 'R':
data[i] = 1;
break;
case 'L':
data[i] = -1;
break;
default:
int t = sc[i];
data[i] = data[t-1];
}
ans+=data[i];
}
printf("%d\n", ans);
}
}
```
## 勘根


[勘根法參考網址](http://edisonx.pixnet.net/blog/post/35777330-%5Bc%E8%AA%9E%E8%A8%80%E6%95%B8%E5%80%BC%E5%88%86%E6%9E%90%5D-%E9%9D%9E%E7%B7%9A%E6%80%A7%E6%96%B9%E7%A8%8B%E5%BC%8F%E6%B1%82%E8%A7%A3---%E5%89%B2%E7%B7%9A%E6%B3%95-s)
## 勘根程式範本
主程式的部分自己寫
```python=
error_threshold = 0.0001
a = -10
b = -9
#當a和b的差距小於error_threshold值就停止程式,
#這裡放要求解的方程式
def f(x):
ans = x**2-6*x+4
return ans
#
# 主程式
#
print(root) #最後印出找到的那個根
```
## 用動態規劃完成Cn取r問題
```python=
def C(n, r):
## 用動態規劃
s = C(4, 2)
print(s)
```