P123: Extract a given number of randomly selected elements from a list
从列表中随机截取指定数量元素。这个的测试用例比较难写,因为任意给定条件的解都不是唯一的,不能简单地比较实际解与预期解。而祇能判断实际解是否属于正确解集合。假设,要从列表l
中随机截取n
个元素,若列表x
符合以下条件则其为该问题的解:
x
的长度为n
x
中每一个元素都属于l
测试用例代码:
from python99.lists.p123 import rnd_select
import functools
import operator
def test_rnd_select():
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
actual = rnd_select(l, 3)
assert len(actual) == 3
assert functools.reduce(
operator.and_, [e in l for e in actual], True) == True
Python标准库提供了random
用于生成pseudo-random(伪随机)数。random
已经提供随机採样方法random.sample(population, k)
。
完整代码实现:
# Extract a given number of randomly selected elements from a list.
# The selected items shall be put into a result list
import random
def rnd_select(l, n):
return random.sample(l, n)