First solution in Clear category for Card Game by colinmcnicholl
from collections import Counter
def cards(deck, hand):
"""My 'first' solution followed approach in the hints which was far from
optimal and not worth modifying to cover the extra tests.
Consequently I have gone for a solution created by morton fox which applies
simple but clear logic which covers all cases.
Input: 'deck' as an integer is the size of the deck.
'hand' as a list of the picked cards. Each element of the list is an
integer representing the face value on one side of the double-sided card.
The numbers on the cards are written according to the following principle:
the first card has 0 and 1, the second - 1 and 2, ..., the n-th
- (n-1) and n.
Function constructs a dictionary whose keys are the face values in the
list 'hand' and whose values are the frequency of these face values in
the 'hand'. Outer loop over all possible cards in a deck of the given size
and inner loop over the two face values each of these cards.
Using the card face value as the dictionary lookup key to return the
frequency of that card value in 'hand'. If the key is in the dictionary
the frequency is decremented by 1 we break from the loop and go back up
to outer loop to get next card, else lookup the value on the other side of
the card and if found in dictionary decrement frequency by 1. Having
completed the outer loop and looked at all possible cards in the given
size of deck if the any of the frequencies are not now 0 then there must
have been a card from another deck in the list of picked cards.
Output: True (if all the viewed cards can be encountered only within
one deck) or False (if otherwise)."""
face_val_counts = Counter(hand)
for card in range(deck):
for num in range(card, card + 2):
face_val_counts[num] -= 1
return sum(face_val_counts.values()) == 0
if __name__ == '__main__':
print(cards(5, [2, 0, 1, 2]))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert cards(5, [2, 0, 1, 2]) == False
assert cards(10, [9, 9, 6, 6]) == True
assert cards(10, ) == False
print("Coding complete? Click 'Check' to earn cool rewards!")
Sept. 28, 2018