DAY 24
2
Software Development

## Day24- 魔鏡啊魔鏡，誰是列表中最美麗的元素? (任意規則的排序方法)

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

``````sudoku= \
["5","3",".",".","7",".",".",".",".",
"6",".",".","1","9","5",".",".",".",
".","9","8",".",".",".",".","6",".",
"8",".",".",".","6",".",".",".","3",
"4",".",".","8",".","3",".",".","1",
"7",".",".",".","2",".",".",".","6",
".","6",".",".",".",".","2","8",".",
".",".",".","4","1","9",".",".","5",
".",".",".",".","8",".",".","7","9"]

ans = solveSudoku(S) # solveSudoku這個函數於昨天的程式有定義
for a in ans:
for i in range(9):
print(s[i*9:i*9+9])
print('---------------') #若有多組解答畫個分隔線
``````

# 排序規則由你定義

## 似魔鏡般的key函數

``````sorted(arr, key= 函數)
``````

key傳進的函數可以將arr裡的元素轉為任何可以比較的結果，

(圖示: 字串`"elephant"`長度=8，字串`"lion"`長度=4、字串`"tiger"`長度=5)

``````arr = ["elephant", "lion", "tiger"]
print(sorted(arr, key=len))
``````

## 技巧1: key參數與lambda的組合技

``````arr = [36,88,125,19]
print(sorted(arr, key= lambda x: x%10))
``````

## 技巧2: 將排序值映射為元組

``````arr = [36,88,125,19]
print(sorted(arr,key= lambda x: (x%2==0, x%10)))
``````

``````arr = [36,88,125,19]
print([(x%2==0, x%10) for x in arr])
``````

# 範例24-1 我的喜好由我定義

``````gifts = ["動感超人", "巧克力餅乾", "球鞋", "百科全書"]
``````

(由於小新可能也會不小心收到討厭的禮物，這個數字也可能是負值)

``````likes = {"動感超人": 2000, "巧克力餅乾":500, "球鞋":800, "百科全書":-100}
``````

``````gifts = ["動感超人", "巧克力餅乾", "球鞋", "百科全書"]
likes = {"動感超人": 2000, "巧克力餅乾":500, "球鞋":800, "百科全書":-100}
``````

# 範例24-2 加權分數

``````scores= [(9, 6, 11), (10, 9, 6), (13, 8, 14), (13, 8, 11), (14, 15, 8)]
``````

``````scores= [(9, 6, 11), (10, 9, 6), (13, 8, 14), (13, 8, 11), (14, 15, 8)]
print(sorted(scores,key= lambda x: x[0]*2+x[1]*3+x[2]))
``````

# 範例24-3 撲克牌大老二之花色點數排序

1. 優先比數字點數，數字2最大，其次是Ace，接下來依數字大小做排序
2. 當數字點數相同時則比較花色，黑桃>紅心>方塊>梅花

(好奇詳細規則者可參考維基百科的說明)

「方塊J」以`"Jd"`表示。

``````hands = ["3c", "Qc", "Js", "Kh", "2h", "5c", "As", "Jd"]
``````

(提示: 用字典記錄花色或點數的價值，例如黑桃=4, 紅心=3, ...)

``````suits = {'c':1, 'd': 2, 'h':3, 's':4}
values= {'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 15}
``````

``````hands = ["3c", "Qc", "Js", "Kh", "2h", "5c", "As", "Jd"]
suits = {'c':1, 'd': 2, 'h':3, 's':4}
values= {'3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 15}
print(sorted(hands, key= lambda c: (values[c[0]],suits[c[1]])))
``````

# 課後練習

(因為是改編，你直接抄Hackerrank的答案是不對的哦，

## 習題: 依指定規則重排字串

input只包含大、小寫字母及數字，規定:

1. 數字一定排在最右邊
2. 偶數一定排在奇數的右邊
3. 大寫字母一定排在小寫字母的右邊
4. 在上述規則下，儘量保持原本字串的順序(在就是在原來字串的index愈大者排愈右邊)

``````input: "Sorting1234"
output: "ortingS1324"
``````

``````s = input() #測試範例輸入 Sorting1234
L=sorted(s, key= ???) #經排序後，L會變成一個字串的列表
print("".join(L)) #預期結果: ortingS1324
``````