小區登記寵物,記下一串種類,比如 ["cat", "dog", "cat"]。寫 count_pets(pets),回傳一個字典:每種寵物有幾隻,按第一次出現的順序。列表是空的就返回 {}。
count_pets(["cat", "dog", "cat"])→{'cat': 2, 'dog': 1}count_pets(["fish", "fish", "fish"])→{'fish': 3}def count_pets(pets):
counts = {}
for pet in pets:
# 在這裡寫:第一次見到記 1,見過就加 1
pass
return counts
寫好了先點「執行」試試示例,沒問題再點「提交」。