Skip to content

Instantly share code, notes, and snippets.

@NotTheEconomist
Last active November 26, 2018 09:15
Show Gist options
  • Save NotTheEconomist/538cd78dd6cf5c1146795e8767bd1ae7 to your computer and use it in GitHub Desktop.
Save NotTheEconomist/538cd78dd6cf5c1146795e8767bd1ae7 to your computer and use it in GitHub Desktop.
Rock Paper Scisccors with deques
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