大爽Python入門教程 4-7 答案
阿新 • • 發佈:2021-11-18
大爽Python入門公開課教案 點選檢視教程總目錄
1 檢查長度
實現一個函式check_any_match_size(words, size)
檢查一個由字串構成的列表words
,
是否存在字串長度符合指定尺寸size
。
任意一個符合尺寸即可返回True
,否則返回False
。
執行時示例如下
>>> check_any_match_size(['lion', 'deer', 'bear'], 5)
False
>>> check_any_match_size(['lion', 'deer', 'sheep'], 5)
True
答案程式碼示例
def check_any_match_size(words, size): for word in words: if len(word) == size: return True return False
2 生成n以內的素數
實現一個函式show_all_prime(n)
返回所有大於等於2,小於n的素數。
執行時示例如下
>>> show_all_prime(10)
[2, 3, 5, 7]
>>> show_all_prime(20)
[2, 3, 5, 7, 11, 13, 17, 19]
答案程式碼示例
def is_prime(num): for i in range(2, num): if num % i == 0: return False return True def show_all_prime(n): res = [] for i in range(2, n): if is_prime(i): res.append(i) return res
3 去重
實現一個函式get_no_repeat(lst)
,
接受一個整陣列成的列表lst
,
返回一個新的列表,其中包含lst
中的元素,但剔除掉了重複項。
>>> get_no_repeat([1,3,5,1,2])
[1, 3, 5, 2]
>>> get_no_repeat([2,3,4,2,3,2,4])
[2, 3, 4]
答案程式碼示例
def get_no_repeat(lst): res = [] for item in lst: if item not in res: res.append(item) return res
4 計算重複字元
實現一個函式get_repeat_str(s1, s2)
,
接受兩個字串s1
, s2
,
返回一個新的字串。
返回的字串由s1
和s2
中的所有相同字元(去除重複)構成,且順序遵循s1
的順序。
>>> get_repeat_str("abcba", "adae")
"a"
>>> get_repeat_str("lihua", "zhangsan")
"ha"
答案程式碼示例
def get_repeat_str(s1, s2):
res = ""
for c in s1:
if c in s2:
if c not in res:
res += c
return res