Skip to content

Instantly share code, notes, and snippets.

@eliotl
Last active September 27, 2019 15:32
Show Gist options
  • Save eliotl/d8b2a97975ec376e080d716f4bebb832 to your computer and use it in GitHub Desktop.
Save eliotl/d8b2a97975ec376e080d716f4bebb832 to your computer and use it in GitHub Desktop.
Implementation of the game described in https://projecteuler.net/problem=503; Paired on with Louis Hyde
import random
class Deck():
def __init__(self, n=3):
self.cards = list(range(1,n+1))
random.shuffle(self.cards)
self.position = 0
def __len__(self):
return len(self.cards)
def _number_of_cards_left(self):
return len(self) - self.position
def draw(self):
assert(self._number_of_cards_left() > 0)
card = self.cards[self.position]
self.position += 1
return card
def alice_draw(self):
previousCards = self.cards[:self.position]
card = self.draw()
previousGreaterCards = len(list(filter(lambda c : card < c, previousCards)))
return (card,previousGreaterCards)
def game(n=3):
deck = Deck(n)
final_score = 0
for turn in range(n):
(card, previousGreaterCards) = deck.alice_draw()
if previousGreaterCards == 1:
verb = "is "
else:
verb = "are "
print("Bob says, \"There " + verb + str(previousGreaterCards) + " previous card that are greater than your card.\"")
if deck._number_of_cards_left() == 0:
print("No cards left! Your score is " + str(card) + "!")
print("The deck was " + str(deck.cards))
final_score = card
break
response = input("Do you want to stop? [y/N] ")
if response.lower() == "y":
print("Your score is " + str(card) + "!")
print("The deck was " + str(deck.cards))
final_score = card
break
else:
print("Drawing another card...")
return final_score
"""
>>> game(6)
Bob says, "There are 0 previous card that are greater than your card."
Do you want to stop? [y/N] n
Drawing another card...
Bob says, "There is 1 previous card that are greater than your card."
Do you want to stop? [y/N] n
Drawing another card...
Bob says, "There are 2 previous card that are greater than your card."
Do you want to stop? [y/N] y
Your score is 1!
The deck was [6, 5, 1, 2, 4, 3]
1
>>> game(6)
Bob says, "There are 0 previous card that are greater than your card."
Do you want to stop? [y/N] n
Drawing another card...
Bob says, "There are 0 previous card that are greater than your card."
Do you want to stop? [y/N] n
Drawing another card...
Bob says, "There is 1 previous card that are greater than your card."
Do you want to stop? [y/N] n
Drawing another card...
Bob says, "There are 2 previous card that are greater than your card."
Do you want to stop? [y/N] y
Your score is 3!
The deck was [2, 6, 4, 3, 1, 5]
3
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment