--- title: 'Python Challenge Day 10 - Total amount of points ' disqus: hackmd --- ## Python Challenge Day 10 - Total amount of points ### DESCRIPTION Our football team has finished the championship. Our team's match results are recorded in a collection of strings. Each match is represented by a string in the format "x:y", where x is our team's score and y is our opponents score. For example: ["3:1", "2:2", "0:1", ...] Points are awarded for each match as follows: if x > y: 3 points (win) if x < y: 0 points (loss) if x = y: 1 point (tie) We need to write a function that takes this collection and returns the number of points our team (x) got in the championship by the rules given above. ### Notes: our team always plays 10 matches in the championship 0 <= x <= 4 0 <= y <= 4 程式邏輯 --- 目的:計算積分數 x 是球隊的得分,y 是對手的得分。 例如:["3:1", "2:2", "0:1", ...] 每場比賽的得分如下: 如果 x > y:3 分(獲勝) 如果 x < y:0 分(損失) 如果 x = y:1 分(平局) 我們需要編寫一個函數來接受這個集合併返回我們的團隊 (x) 根據上面給出的規則在錦標賽中獲得的積分數,且在錦標賽中打了 10 場比賽。 0 <= x <= 4 0 <= y <= 4 ### Practice 1: ``` python def points(games): count = 0 for i in games: if int(i[0]) > int(i[2]): count += 3 elif int(i[0]) == int(i[2]): count += 1 return count ``` * 計算總積分,需要定義一個元素去放積分的加總 count=0 * 用for迴圈計算; for 和 in 是 Python 的關鍵字,這兩個關鍵字之間會放我們自訂的變數,而 in的後面則可接一個序列 (Sequence),迴圈會依序從序列 (例如: 一連串清單資料,一組數字或一個名單) 裡取得元素,並將元素指派給前面自訂的變數,然後執行迴圈裡的內容。 例如: ["3:1"] ["元素0是3,元素1是:,元素2是1"] ### Practice 2: ``` python def points(games): count = 0 for score in games: res = score.split(':') if res[0]>res[1]: count += 3 elif res[0] == res[1]: count += 1 return count ``` * 用split分隔':',讓比分成為各兩個元素 ## 參考資源 :::info * [Kata](https://www.codewars.com/kata/5bb904724c47249b10000131) :::