100+Python挑战性编程练习系列 -- day 17
Question 63
请编写断言语句以验证列表 [2,4,5,6] 中的每个数字是否为偶数。
data = [2,4,5,6] for i in data: assert i%2 == 0, "{} is not an even number".format(i) Question 64
请编写一个接受控制台基本数学表达式的程序,并打印评估结果。
示例:如果给出以下 n 作为程序的输入:
35 + 3
然后,程序的输出应该是:
38
expression = input() ans = eval(expression) print(ans) Question 65
请编写一个二分搜索函数,用于搜索排序列表中的项目。该函数应返回要在列表中搜索的元素的索引。
def binary_search(lst, item): low = 0 high = len(lst) - 1 while low <= high: mid = round((low + high) / 2) if lst[mid] == item: return mid elif lst[mid] > item: high = mid - 1 else: low = mid + 1 return None lst = [1,3,5,7,] print(binary_search(lst, 9)) Question 66
请使用 Python 模块生成一个随机浮点数,其中值介于 10 和 100 之间。
import random rand_num = random.uniform(10,100) print(rand_num)