DAY 13
3
Software Development

## Day13- 第二屠龍刀二式- 列表生成式(二) 搭配if使用達到過濾的效果

(還沒看過題目的朋友歡迎點昨日題目傳送門)

``````def findMin(N, W):
return min([min(w) for w in W])
``````

min()函數無法直接取得二維list的最小值，

(其實參數N是可以不用的，別被題目誤導囉)

# 搭配if使用達到過濾的效果

``````新列表 = [something for x in 舊列表(或可迭代物件) if 條件判斷句]
``````

## 取出列表中的偶數

``````>>> L=[18, 73, -24, 6, 34, -87, -17, -98, -53, 16]
>>> [x for x in L if x%2==0]
[18, -24, 6, 34, -98, 16]
``````

## 取出列表中的負數

``````>>> [x for x in L if x<0]
[-24, -87, -17, -98, -53]
``````

## 取出列表中的字串型態

(註: 內建函數isinstance(x, type)可以判斷前者是否為後者的變數型態)

``````>>> M = ["Horse","Tiger",25,6.2,"Tomato"]
>>> [x for x in M if isinstance(x, str)]
['Horse', 'Tiger', 'Tomato']
``````

# 複習: 三元運算子- 簡化的if-else 語句

``````if 條件成立:
變數= 值1
else:
變數= 值2
``````

``````變數 = 值1 if 條件成立 else值2
``````

``````num = int(input())
print(f"{num} 是 3 的倍數" if num % 3 ==0 else f"{num} 不是 3 的倍數")
``````

# 範例13-1 阿明買蛋糕

(如果買不起蛋糕則回傳 `-1`)

### 例子1:

``````nums = [100,200,500,2000]
K = 1000
Output: 700
``````

(注意不能買2個500元的蛋糕，因為500元的蛋糕只有一個。)

### 例子2:

``````nums = [100,200,500,2000]
K = 200
Output: -1
``````

``````def mostValue(nums, K):
L=[nums[i]+nums[j] for i in range(len(nums)) for j in range(i+1,len(nums)) if nums[i]+nums[j]<=K]
return max(L) if len(L)>0 else -1
``````

``````nums = [100,200,500,2000]
print(mostValue(nums, 1000))
print(mostValue(nums, 200))
``````

`700`
`-1`

# 範例13-2 聽說好課值得一修再修?

``````scores = [20,30,50,60,25,70]
``````

``````scores = [20,30,50,60,25,70]
passed = ["及格" if s>=60 else "需要重修" for s in scores]
print(passed) #['需要重修', '需要重修', '需要重修', '及格', '需要重修', '及格']
``````

# 範例13-3 判斷質數

``````def isPrime(n):
pass
``````

## 解法一:

``````def isPrime(n):
return len([i for i in range(1,n+1) if n%i==0])==2
``````

## 解法二:

``````def isPrime(n):
return sum([1 if n%i==0 else 0 for i in range(1,n+1)])==2
``````

``````for i in range(1,10):
print(f'{i}是質數?: {isPrime(i)}')
``````

``````1是質數?: False
2是質數?: True
3是質數?: True
4是質數?: False
5是質數?: True
6是質數?: False
7是質數?: True
8是質數?: False
9是質數?: False
``````

``````print(isPrime(10 ** 8))
``````

(時間因電腦效能而異，跑個好幾十秒可能也是正常的)

# 少年啊，我將最精華的兩把python屠龍刀都傳給你了，多看多實作吧

「切片」與「列表生成式」傳授給各位了，

## 課後習題- 韓信的千軍萬馬

``````def soldiers(m, n):
return #這邊寫你要回傳的值
``````

``````輸入: m = 20, n=200

``````