Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. from random import randint
  2. from functools import partial
  3. from collections import Counter
  4. from itertools import cycle
  5. from typing import Iterable
  6.  
  7. # única función random que se permite usar
  8. rand5 = partial(randint, 1, 5)
  9.  
  10. # yapf: disable
  11. # matriz de conversión
  12. conv = [
  13. [1, 2, 3, 4, 5],
  14. [6, 7, 1, 2, 3],
  15. [4, 5, 6, 7, 1],
  16. [2, 3, 4, 5, 6],
  17. [7, 0, 0, 0, 0]
  18. ]
  19. # yapf: enable
  20.  
  21.  
  22. def rand7() -> int:
  23. """
  24. Generador aleatorio de números en rango [1,7]
  25. a partir de randint(1,5)
  26. """
  27.  
  28. res = 0
  29. while not res:
  30.  
  31. # tomamos dos números aleatorios en el rango [1,5]
  32. (a, b) = (rand5(), rand5())
  33.  
  34. # buscamos su correspondencia en el rango [1,7]
  35. res = conv[a - 1][b - 1]
  36.  
  37. return res
  38.  
  39.  
  40. def rand7_gen() -> Iterable[int]:
  41. """
  42. Generador aleatorio de números en rango [1,7]
  43. a partir de randint(1,5). Versión optimizada.
  44. """
  45.  
  46. cycle7 = cycle((i, j) for i in range(1, 8) for j in range(1, 8))
  47. conv = [[[next(cycle7) for i in range(5)] for j in range(5)]
  48. for k in range(5)]
  49.  
  50. while True:
  51.  
  52. # tomamos tres números aleatorios en el rango [0,4]
  53. (a, b, c) = (rand5() - 1, rand5() - 1, rand5() - 1)
  54. num = a * 5**2 + b * 5 + c
  55.  
  56. if num < 2 * 7**2:
  57. (r, s) = conv[a][b][c]
  58. yield r
  59. yield s
  60.  
  61.  
  62. def test_rand(r, *, N=70000):
  63. media = N / 7
  64. frecuencias = Counter(r() for _ in range(N))
  65.  
  66. print(frecuencias)
  67. print(", ".join(f"{(v - media) / media :.2%}"
  68. for v in frecuencias.values()))
  69.  
  70.  
  71. if __name__ == "__main__":
  72. print("Randin(1,7) nativo")
  73. test_rand(partial(randint, 1, 7))
  74.  
  75. print("Randin(1,7) generado")
  76. test_rand(rand7)
  77.  
  78. print("Randin(1,7) generado2")
  79. r = rand7_gen()
  80. test_rand(partial(next, r))
  81.  
  82. print("Randin(1,7) generado2")
  83. r = rand7_gen()
  84. test_rand(partial(next, r), N=140000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement