proffreda

dice.py

Sep 8th, 2016
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. """Higher Order Functions used for simulations of dice rolls.
  2.  
  3. Definition: An n-sided dice function takes no arguments and always returns an int from 1 to n, inclusive.
  4.  
  5. Types of n-sided dice functions:
  6. - Randomized: a randomized dice function can be fair, meaning that ir produce each possible outcome
  7. from 1 to n with equal probability. Examples: four_sided, six_sided
  8. - Deterministic: a deterministic dice function will be used for testing. Deterministic test dice functions always cycle
  9. through a fixed sequence of n values.
  10. - We write a make_fair_dice higher-order function to return a fair, randomized n-sided dice function.
  11. - We write a make_test_dice higher-order function that will return a deterministic, testing n-sided dice function.
  12. """
  13.  
  14. from random import randint
  15.  
  16. def make_fair_dice(n):
  17. """Returns an n-sided fair dice function."""
  18. assert type(n) == int and n >= 1, 'Illegal value for number of sides'
  19. def dice():
  20. return randint(1,n)
  21. return dice
  22.  
  23. four_sided = make_fair_dice(4)
  24. six_sided = make_fair_dice(6)
  25.  
  26. def make_test_dice(*outcomes):
  27. """Return an n-sided dice function that cycles deterministically through outcomes - a rest parameter.
  28.  
  29. >>> dice = make_test_dice(4, 1, 3)
  30. >>> dice(), dice(), dice(), dice()
  31. (4, 1, 3, 4)
  32.  
  33. """
  34. assert len(outcomes) > 0, 'You must supply outcomes to make_test_dice'
  35. for o in outcomes:
  36. assert type(o) == int and o >= 1, 'Outcome is not a positive integer'
  37. index = len(outcomes) - 1
  38. def dice():
  39. nonlocal index
  40. index = (index + 1) % len(outcomes)
  41. return outcomes[index]
  42. return dice
Advertisement
Add Comment
Please, Sign In to add comment