###### tags: `Python` `code`
# 221204 Python聯課
---
## Homework
### xor
```python=
a = int(input())
b = int(input())
if (a or b) and (a != b):
print(True)
else:
print(False)
```
## 迴圈
#### 練習1003-印星星
```python=
```
### while-loop
> 大壯覺得一天三餐太少了,他決定要做個隨時都能點餐的系統
```python=
"""
# while + 布林值
常見statement
- while True
- while + 變數
- while + 條件式
流程控制
- break
- continue
- pass
"""
hungry = True
while hungry:
print('1.Hamburger Combo 2.Coffee')
food = int(input('What do you want to eat?'))
if food == 1:
hungry = False
```
- `break`:跳出迴圈
- `continue`:跳過後面處理,回到開始
- `pass`:不處理

[圖片來源](https://www.programiz.com/python-programming/break-continue)
#### 流程控制
```python=
"""
印1~10 但不印3
"""
a = 0
while True:
a = a + 1
if a == 3:
continue
print(a)
if a == 10:
break
```
pass通常這樣用
```python=
while True:
pass
if xxx:
pass
```
- 會用在想好程式架構但還沒有要寫的時候(反正基本上沒什麼人在用XD)
---
## 容器
| 容器 | 有/無序 | 修正 | 函式 | 特色 |
| ---- | ------- |:----:| ------- | --- |
| 元組 | 有序 | X | tuple() | 不可修改資料 |
| **序列** | 有序 | O | list() | 最常用|
| **字典** | 無序 | O | dict() | 依鍵取值 |
| 集合 | 無序 | O | set() | 刪除重複資料 |
### `list`
- 最外層用中括號
- 同個列表中的資料型態可以不一樣
- 可以為數字、字串甚至是tuple, dict等
常用方法
| 方法 | 功能 |
| ---------------------- | ------------------------------------------------------- |
| **`lst.append(x)`** | 將元素x加入lst尾部 |
| `lst.extend(alist)` | 將列表alist裡面所有元素加入lst |
| `lst.insert(index, x)` | 在lst指定位置index處加入元素x,其後所有元素向後一個位置 |
| `del lst[index]` | 刪除指定index資料 |
| `lst.remove(x)` | 刪掉lst中首次出現元素x |
| `lst.clear()` | 將lst清空 |
| **`lst.count(x)`** | 計算元素x在lst中出現次數 |
| **`lst.sort()`** | 將lst內的元素進行排序 |
| `lst.reverse()` | 將lst內的元素進行翻轉 |
| **`sorted(lst)`** | 將lst內的元素進行排序,但要另外用變數存 |
| **`sum(lst)`** | 針對一維數字list進行加總 |
#### 基礎設定
```python=
# 直接設定
alist = [1, 2, 3, 4, 5]
# 設定空的list,再增加
blist = []
clist = list()
print(alist)
print(blist)
print(clist)
print(type(alist))
```
#### 新增資料 ex(3)
```python=
# 新增資料
blist.append(1)
print(blist)
# list相加
blist = blist + [2]
print(blist)
blist.extend([3, 5])
print(blist)
# insert(index, element)
blist.insert(3, 4)
print(blist)
```
```python=
# 練習:請用for迴圈搭配某個方法讓blist = [1,2,3,4,5]
for i in range(1, 6):
print(i)
clist.append(i)
print(clist)
```
#### 取資料
```python=
# 輸出指定index的資料
print(blist[2])
# 取第一個元素
b = blist.pop()
print(b, blist)
```
#### 刪除資料
```python=
# 刪除指定index資料
del blist[1]
print(blist)
# 移除第一個3
blist.remove(3)
# blist.remove(2)
# ValueError: list.remove(x): x not in list
print(blist)
# 全部清除
blist.clear()
print(blist)
```
#### 可以用 `list()` 將其他資料轉成list
```python=
# 將string轉成list
print(list('abcdefghijklmnopqrstuvwxyz'))
print(list('hello world'))
# 將range()物件轉為list之練習一的不同寫法
print(list(range(1, 6)))
```
#### 其他常用方法
用for-loop讀list中的資料
```python=
alist = list('hello world')
for i in alist:
print(i)
```
用 `len()` 計算list中有多少資料
```python=
alist = list('hello world')
print(len(alist))
```
排序 ex1005(10)
```python=
# 原地倒序
nums = list(range(1, 6))
nums.reverse()
print(nums)
# 原地排序
nums.sort()
print(nums)
# 另存排序
nums = sorted(nums)
print(nums)
# 另存倒序
nums = sorted(nums, reverse=True)
print(nums)
```
`lst.count()` `sum(lst)` ex1006(5)
```python=
alist = [41, 69, 6, 45, 23, 32, 50, 16, 46, 91,
24, 41, 76, 40, 47, 95, 16, 28, 85, 14,
85, 24, 83, 2, 55, 19, 13, 21, 74, 97,
95, 52, 7, 21, 66, 21, 18, 1, 58, 93,
86, 9, 16, 30, 81, 14, 92, 80, 82, 70]
print(alist.count(16))
print(sum(alist))
```
#### index
- 從0開始
- 用來取資料
- 負的 -> 從最後一個開始
#### [練習1005](https://zerojudge.tw/ShowProblem?problemid=e155)
:::success
給你一副照順序放好的紙牌,其中卡片的編號從1~n,且1號排在最上面,n號牌在最底下。
只要這副牌還有兩張以上,你就必須照以下的規則操作:
丟掉最上面的那張牌,然後把目前最上面的那張牌放到牌堆的最下面。
你的工作是找出每張牌被丟掉的順序,以及最後剩下的那張牌。
輸入的每一列包含一個整數 n≤50,當輸入為0時代表輸入結束,你不應該處理這個輸入。
對每個輸入的數字產生兩列輸出,第一列是每張牌被丟掉的順序,第二列則是剩下的那張牌。
任何一列都不應該有任何前置或尾隨的多餘空白,輸出細節請參考sample output。
**輸入**
7
19
10
6
0
**輸出**
Discarded cards: 1, 3, 5, 7, 4, 2
Remaining card: 6
Discarded cards: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 4, 8, 12, 16, 2, 10, 18, 14
Remaining card: 6
Discarded cards: 1, 3, 5, 7, 9, 2, 6, 10, 8
Remaining card: 4
Discarded cards: 1, 3, 5, 2, 6
Remaining card: 4
:::
```python=
# zerojudge e155
while True:
n = int(input())
if n==0:
break
cards = list(range(1, n+1))
d = []
while True:
d.append(cards.pop(0))
if len(cards) == 1:
break
cards.append(cards.pop(0))
print('Discarded cards:', ', '.join(map(str, d)))
print('Remaining cards:', cards[0])
```
##### `map(function, data)` `''.join(data)`
```python=
d = [1, 2, 3, 4, 5]
d = map(str, d)
print(d)
d = list(map(str, d))
print(d)
print(''.join(d))
```
#### 練習1006
```python=
"""
# 請參考count例題
# 1) 計算alist中有幾個21
# 2) 將alist由大到小排序
# 3) bonus: 計算alist中有幾種不同數字
"""
alist = [41, 69, 6, 45, 23, 32, 50, 16, 46, 91,
24, 41, 76, 40, 47, 95, 16, 28, 85, 14,
85, 24, 83, 2, 55, 19, 13, 21, 74, 97,
95, 52, 7, 21, 66, 21, 18, 1, 58, 93,
86, 9, 16, 30, 81, 14, 92, 80, 82, 70]
alist = sorted(alist, reverse=True)
cnt = 0
temp = -1
for i in alist:
if i!= temp:
temp = i
cnt += 1
print(alist)
print(cnt)
```
### `tuple()`
- 資料不可變更,又稱常數列表
- 存取/處理資料速度比list快
- list能做的它幾乎都行
```python=
# 用一對小括號設定
atup = (2, 1, 3)
print(type(atup))
print()
# 如果值有一個元素,要在後面加,
# 否則將視為btup = 3
btup = (3)
print(type(btup))
btup = (3, )
print(type(btup))
print()
# 設定空的tuple
ctup = ()
dtup = tuple()
print('ctup: ', ctup)
print('dtup: ', dtup)
print()
# 用index取資料
print('atup[0]: ', atup[0])
print()
# 用 for-loop讀取資料
print('for-loop')
for i in atup:
print(i)
print()
# 排序:只能用sorted(atup),且會變成list
print('after sort')
print(sorted(atup))
print()
# 加總
print('sum')
print(sum(atup))
print()
# 長度
print('length')
print(len(atup))
```
### `set()`
#### 設定
```python=
aset = {3, 5}
bset = {3, 5, 5, 3, 3, 5}
print(type(aset))
```
- `aset` 和 `bset` 一樣嗎
- 集合內的每個元素都是唯一的
#### 新增
```python=
aset = {3, 5}
aset.add(4)
```
#### 常見用途-去除重複資料
```python=
bset = set([0, 4, 5, 4, 6, 2, 7, 9, 3, 4, 2])
print(bset)
```
請用 `set()` 的概念完成剛剛的練習1006
```python=
alist = [41, 69, 6, 45, 23, 32, 50, 16, 46, 91,
24, 41, 76, 40, 47, 95, 16, 28, 85, 14,
85, 24, 83, 2, 55, 19, 13, 21, 74, 97,
95, 52, 7, 21, 66, 21, 18, 1, 58, 93,
86, 9, 16, 30, 81, 14, 92, 80, 82, 70]
aset = set(alist)
print(len(aset))
```
### `dict()`
- 依鍵取值
| 函式 | 功能 |
| -------- | -------- |
| `adict.items()` | 返回所有元素 |
| `adict.keys()` | 返回所有元素 |
| `adict.values()` | 返回所有元素 |
#### 基礎操作
```python=
# 設定dictionary
adict = {'Sam': 95, 'Albert': 80, 'Hanna': 60}
print(adict)
# 空dict
bdict = {}
cdict = dict()
# 新增
adict['Sally'] = 20
print(adict)
```
#### 讀取資料
```python=
# 讀取單個元素的值:用key對應value
print(adict['Sam'])
# 若不存在會返回錯誤
# print(adict['Molly'])
print('items', adict.items())
print('keys', adict.keys())
print('values', adict.values())
# 常見用法
if 'Sam' in adict.keys():
print(adict['Sam'])
for i in adict.keys():
print(i, adict[i])
print()
for k, v in adict.items():
print(k, v)
```
#### 排序
```python=
adict = {'Sam': 95,
'Molly': 80,
'Albert': 80,
'Hanna': 65,
'Sally': 20}
# 這樣只排到key
print(sorted(adict))
print(sorted(adict.keys()))
# 這樣會根據key排序,順便把value印出來
print(sorted(adict.items()))
# 但我想要由成績來排序?
# 比較抽象,就...盡量看:P
# 由高到低
print(sorted(adict.items(), key=lambda x:x[1]))
# 由低到高:加上負號,這只限數字類型能用
print(sorted(adict.items(), key=lambda x:-x[1]))
# 常見寫法:先按分數降冪,若相同再按名字升冪
print(sorted(adict.items(), key=lambda x:(-x[1], x[0])))
```
[lambda的補充](https://www.w3schools.com/python/python_lambda.asp)