DAY 10
2
Software Development

## Day10- 幾個程式經典問題，一亮出第一屠龍刀，彷彿開著坦克車攻打原始人，太逆天啦 (談切片語法的應用)

Day8中給大家講解了切片運算與range()函數的基礎語法，

## 範例10-1: 天才發明的倒裝句

``````刷牙<->牙刷

dog<->god
desserts(甜點) <-> stressed(壓力)
live(生命) <-> evil(邪惡)
``````

``````def reverseStr(s):
return s[::-1]

print(reverseStr("desserts")) # stressed
print(reverseStr("刷牙")) #刷牙
``````

## 範例10-2: 判斷迴文字串

``````def isPalindrome(s):
return s==s[::-1]

print(isPalindrome("level")) # True
print(isPalindrome("deep")) #False
print(isPalindrome("上海自來水來自海上")) # True
``````

## 範例10-3: 完美洗牌程序

### 純樸的解法

``````def pefectShuffle(deck):
n= len(deck)//2
first = deck[:n]  #取出前n個數字當做第一副牌
second = deck[n:] #取出後n個數字當做第二副牌
nextIsFirst= True  #記錄下一張要發的牌是第一副牌還是第二副
firstIdx=0        #記錄下一張要發的牌的index
secondIdx=0       #記錄下一張要發的牌的index
for i in range(2*n):
if nextIsFirst:
deck[i]=first[firstIdx]
firstIdx+=1
else:
deck[i]=second[secondIdx]
secondIdx+=1
nextIsFirst= not nextIsFirst
``````

``````deck=list(range(1,9)) #[1,2,3,4,5,6,7,8]
pefectShuffle(deck)
print(deck)
``````

``````pefectShuffle(deck)
print(deck)
``````

``````print(pefectShuffle(deck))
``````

### 高級切片語法

``````def pefectShuffle(deck):
n= len(deck)//2
deck[::2], deck[1::2]= deck[:n], deck[n:]
``````

``````deck=list(range(1,9)) #[1,2,3,4,5,6,7,8]
pefectShuffle(deck)
print(deck)
``````

# 本篇結語

## 參考資料

``````字串倒轉 => s[::-1]，一行解

deck[::2], deck[1::2]= deck[:n], deck[n:]，兩行解。
``````

(明天會先介紹一些關於python容器的特性)

# 課後練習- 關於切片高級語法

``````deck[::2], deck[1::2]= deck[:n], deck[n:]
``````

``````A = [1,2,3,4,5,6]
B = [1,2,3,4,5,6]
C = ['A','B','C']

A[::2] = C[:] #把A的偶數項換成'A','B','C'
B[1:3] = C[:]
print(A)
print(B)
``````

`['A', 2, 'B', 4, 'C', 6]`
`[1, 'A', 'B', 'C', 4, 5, 6]`

``````A = [1,2,3,4]
C = ['A','B','C']

A[::2] = C[:] #ValueError
``````

## 習題

(你想用數學解或直接用程式驗證皆可)

``````A = [0] * 30
A[::3] = [1] * len(A[::3])
A[::5] = [1] * len(A[::5])
``````