Last active
November 26, 2018 09:15
-
-
Save NotTheEconomist/538cd78dd6cf5c1146795e8767bd1ae7 to your computer and use it in GitHub Desktop.
Rock Paper Scisccors with deques
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
def rps(*choices): | |
"""choices must be in order so that each proceeding element defeats its neighbor. | |
Returns a function that takes two members of choices and decides which one would win in that RPS game. | |
rps("rock", "paper", "scissors") or rps("paper", "scissors", "rock"), but never rps("scissors", "paper", "rock") | |
""" | |
assert len(choices) % 2 == 1, "Length of choices should always be odd." | |
matrix = collections.deque(choices) | |
midpoint = len(choices) // 2 | |
def who_wins(a, b): | |
if a==b: | |
return "Tie." | |
rotate_length = midpoint - matrix.index(a) | |
matrix.rotate(rotate_length) # a is now in the middle | |
b_index = matrix.index(b) # so we know that... | |
if midpoint < b_index: | |
return f"{b} beats {a}" | |
else: | |
return f"{a} beats {b}" | |
return who_wins | |
def main(): | |
game = rps("rock", "paper", "scissors") | |
result = game("scissors", "rock") | |
print(result) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment