P123: Extract a given number of randomly selected elements from a list

从列表中随机截取指定数量元素。这个的测试用例比较难写,因为任意给定条件的解都不是唯一的,不能简单地比较实际解与预期解。而祇能判断实际解是否属于正确解集合。假设,要从列表l中随机截取n个元素,若列表x符合以下条件则其为该问题的解:

  1. x的长度为n
  2. 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)

results matching ""

    No results matching ""