705_random.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import random as r
  2. r.seed(10)
  3. for _ in range(100):
  4. i = r.randint(1, 10)
  5. assert i <= 10
  6. assert i >= 1
  7. i = r.random()
  8. assert 0.0 <= i <= 1.0
  9. i = r.uniform(3.0, 9.5)
  10. assert 3.0 <= i <= 9.5
  11. a = [1, 2, 3, 4]
  12. r.shuffle(a)
  13. for i in range(10):
  14. assert r.choice(a) in a
  15. for i in range(10):
  16. assert r.choice(tuple(a)) in a
  17. for i in range(10):
  18. assert r.choice('hello') in 'hello'
  19. for i in range(10):
  20. assert r.randint(1, 1) == 1
  21. # test choices
  22. x = (1,)
  23. res = r.choices(x, k=4)
  24. assert (res == [1, 1, 1, 1]), res
  25. w = (1, 2, 3)
  26. assert r.choices([1, 2, 3], (0.0, 0.0, 0.5)) == [3]
  27. try:
  28. r.choices([1, 2, 3], (0.0, 0.0, 0.5, 0.5))
  29. exit(1)
  30. except ValueError:
  31. pass
  32. try:
  33. r.choices([])
  34. exit(1)
  35. except IndexError:
  36. pass
  37. seq = [1, 2, 3, 4]
  38. weights = [0.1, 0.2, 0.2, 0.5]
  39. k = 1000
  40. res = r.choices(seq, weights, k=k)
  41. assert len(res) == k and isinstance(res, list)
  42. max_error = 0.03
  43. for i in range(len(seq)):
  44. actual_w = res.count(seq[i]) / k
  45. assert abs(actual_w - weights[i]) < max_error
  46. # test seed
  47. from random import randint, seed
  48. seed(7)
  49. a = randint(1, 100)
  50. b = randint(-2**60, 1)
  51. c = randint(50, 100)
  52. assert (a, b, c) == (16, -418020281577586157, 76)
  53. seed(7)
  54. assert a == randint(1, 100)
  55. assert b == randint(-2**60, 1)
  56. assert c == randint(50, 100)
  57. import random
  58. assert random.Random(7).randint(1, 100) == a