Решение на Тесте карти от Тихомир Янев

Обратно към всички решения

Към профила на Тихомир Янев

Резултати

  • 10 точки от тестове
  • 0 бонус точки
  • 10 точки общо
  • 16 успешни тест(а)
  • 0 неуспешни тест(а)

Код

import collections
class Suit:
@property
def color(self):
return 'black' if self.label in {'Clubs', 'Spades'} else 'red'
class Rank:
@property
def symbol(self):
return SYMBOLS[self.label]
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return str(self.rank) == str(other.rank) and str(
other.suit) == str(self.suit)
def __str__(self):
return '{} of {}'.format(str(self.rank), str(self.suit))
def __setattr__(self, attr, _):
raise AttributeError("can't set attribute")
class CardCollection:
def __init__(self, collection = []):
self.cards = [x for x in collection]
def __len__(self):
return len(self.cards)
def __getitem__(self, index):
if index < len(self.cards): return self.cards[index]
raise IndexError
def add(self, card):
self.cards.append(card)
def draw(self, index):
return self.cards.pop(index)
def draw_from_top(self):
return self.draw(len(self.cards) - 1)
def draw_from_bottom(self):
return self.draw(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
for i in range(0, len(self.cards)):
if self.cards[i] == card: return i
raise ValueError('{} is not in list'.format(card))
def StandardDeck():
return [Card(rank, suit) for suit in SUITS.values()
for rank in RANKS.values()]
def BeloteDeck():
return [Card(rank, suit) for suit in SUITS.values()
for rank in RANKS.values() if rank().symbol
not in {'2', '3', '4', '5', '6'}]
def SixtySixDeck():
return [Card(rank, suit) for suit in SUITS.values()
for rank in RANKS.values() if rank().symbol
not in {'2', '3', '4', '5', '6', '7', '8'}]
def to_str(cls):
return cls.label
def equal(cls, other):
return cls.label == other.label
SYMBOLS = collections.OrderedDict([
('King', 'K'), ('Queen', 'Q'), ('Jack', 'J'),
('Ten', '10'), ('Nine', '9'), ('Eight', '8'),
('Seven', '7'), ('Six', '6'), ('Five', '5'),
('Four', '4'), ('Three', '3'), ('Two', '2'),
('Ace', 'A')])
SUIT_LIST = ['Diamonds', 'Clubs', 'Hearts', 'Spades']
RANKS = collections.OrderedDict([(x, type(x, (Rank,),
{'label': x, '__str__': to_str,
'__eq__': equal})) for x in SYMBOLS.keys()])
SUITS = collections.OrderedDict([(x, type(x, (Suit,),
{'label': x, '__str__': to_str,
'__eq__': equal})) for x in SUIT_LIST])

Лог от изпълнението

................
----------------------------------------------------------------------
Ran 16 tests in 0.022s

OK

История (2 версии и 2 коментара)

Тихомир обнови решението на 22.03.2014 01:46 (преди около 10 години)

+class Suit:
+ def __str__(self):
+ return self.label
+
+ def __eq__(self, other):
+ return self.label == other.label
+
+ @property
+ def color(self):
+ return 'black' if self.label in {'Clubs', 'Spades'} else 'red'
+
+class Rank:
+ def __str__(self):
+ return self.label
+
+ def __eq__(self, other):
+ return self.label == other.label
+
+ @property
+ def symbol(self):
+ return SYMBOLS[self.label]
+
+class Card:
+ def __init__(self, rank, suit):
+ object.__setattr__(self, 'rank', rank())
+ object.__setattr__(self, 'suit', suit())
+
+ def __eq__(self, other):
+ return str(self.rank) == str(other.rank) and str(
+ other.suit) == str(self.suit)
+
+ def __str__(self):
+ return '{} of {}'.format(str(self.rank), str(self.suit))
+
+ def __setattr__(self, attr, _):
+ raise AttributeError("can't set attribute")
+
+class CardCollection:
+ def __init__(self, collection = []):
+ self.cards = []
+ for card in collection: self.add(card)
+
+ def __len__(self):
+ return len(self.cards)
+
+ def __getitem__(self, index):
+ if index < len(self.cards): return self.cards[index]
+ raise IndexError
+
+ def add(self, card):
+ self.cards.append(card)
+
+ def draw(self, index):
+ card = self.cards[index]
+ del self.cards[index]
+ return card
+
+ def draw_from_top(self):
+ return self.draw(len(self.cards) - 1)
+
+ def draw_from_bottom(self):
+ return self.draw(0)
+
+ def top_card(self):
+ return self.cards[-1]
+
+ def bottom_card(self):
+ return self.cards[0]
+
+ def index(self, card):
+ for i in range(0, len(self.cards)):
+ if self.cards[i] == card: return i
+ raise ValueError('{} is not in list'.format(card))
+
+def StandardDeck():
+ return [Card(rank, suit) for rank in RANKS.values()
+ for suit in SUITS.values()]
+
+def BeloteDeck():
+ return [Card(rank, suit) for rank in RANKS.values()
+ for suit in SUITS.values() if rank().symbol
+ not in {'2', '3', '4', '5', '6'}]
+
+def SixtySixDeck():
+ return [Card(rank, suit) for rank in RANKS.values()
+ for suit in SUITS.values() if rank().symbol
+ not in {'2', '3', '4', '5', '6', '7', '8'}]
+
+SYMBOLS = {'King': 'K', 'Queen': 'Q', 'Jack' : 'J',
+ 'Ten': '10', 'Nine': '9', 'Eight': '8',
+ 'Seven': '7', 'Six': '6', 'Five': '5',
+ 'Four' : '4', 'Three' : '3', 'Two': '2', 'Ace': 'A'}
+
+SUIT_SET = {'Diamonds', 'Clubs', 'Spades', 'Hearts'}
+
+RANKS = dict([(x, type(x, (Rank,), {'label': x}))
+ for x in SYMBOLS.keys()])
+SUITS = dict([(x, type(x, (Suit,), {'label': x})) for x in SUIT_SET])
  • Защо правиш това object.__setattr__(self, 'rank', rank())? В python си има синтаксис за тази операция
  • Не правиш for-ове и if-ове на един ред
  • Виж list.pop, това ще ти помогне да имплементираш CardCollection.draw като хората
  • Тестетата си имат строго определен ред

Тихомир обнови решението на 25.03.2014 00:51 (преди около 10 години)

-class Suit:
- def __str__(self):
- return self.label
+import collections
- def __eq__(self, other):
- return self.label == other.label
-
+class Suit:
@property
def color(self):
return 'black' if self.label in {'Clubs', 'Spades'} else 'red'
class Rank:
- def __str__(self):
- return self.label
-
- def __eq__(self, other):
- return self.label == other.label
-
@property
def symbol(self):
return SYMBOLS[self.label]
class Card:
def __init__(self, rank, suit):
object.__setattr__(self, 'rank', rank())
object.__setattr__(self, 'suit', suit())
def __eq__(self, other):
return str(self.rank) == str(other.rank) and str(
other.suit) == str(self.suit)
def __str__(self):
return '{} of {}'.format(str(self.rank), str(self.suit))
def __setattr__(self, attr, _):
raise AttributeError("can't set attribute")
class CardCollection:
def __init__(self, collection = []):
- self.cards = []
- for card in collection: self.add(card)
+ self.cards = [x for x in collection]
def __len__(self):
return len(self.cards)
def __getitem__(self, index):
if index < len(self.cards): return self.cards[index]
raise IndexError
def add(self, card):
self.cards.append(card)
def draw(self, index):
- card = self.cards[index]
- del self.cards[index]
- return card
+ return self.cards.pop(index)
def draw_from_top(self):
return self.draw(len(self.cards) - 1)
def draw_from_bottom(self):
return self.draw(0)
def top_card(self):
return self.cards[-1]
def bottom_card(self):
return self.cards[0]
def index(self, card):
for i in range(0, len(self.cards)):
if self.cards[i] == card: return i
raise ValueError('{} is not in list'.format(card))
def StandardDeck():
- return [Card(rank, suit) for rank in RANKS.values()
- for suit in SUITS.values()]
+ return [Card(rank, suit) for suit in SUITS.values()
+ for rank in RANKS.values()]
def BeloteDeck():
- return [Card(rank, suit) for rank in RANKS.values()
- for suit in SUITS.values() if rank().symbol
- not in {'2', '3', '4', '5', '6'}]
+ return [Card(rank, suit) for suit in SUITS.values()
+ for rank in RANKS.values() if rank().symbol
+ not in {'2', '3', '4', '5', '6'}]
def SixtySixDeck():
- return [Card(rank, suit) for rank in RANKS.values()
- for suit in SUITS.values() if rank().symbol
- not in {'2', '3', '4', '5', '6', '7', '8'}]
+ return [Card(rank, suit) for suit in SUITS.values()
+ for rank in RANKS.values() if rank().symbol
+ not in {'2', '3', '4', '5', '6', '7', '8'}]
-SYMBOLS = {'King': 'K', 'Queen': 'Q', 'Jack' : 'J',
- 'Ten': '10', 'Nine': '9', 'Eight': '8',
- 'Seven': '7', 'Six': '6', 'Five': '5',
- 'Four' : '4', 'Three' : '3', 'Two': '2', 'Ace': 'A'}
+def to_str(cls):
+ return cls.label
-SUIT_SET = {'Diamonds', 'Clubs', 'Spades', 'Hearts'}
+def equal(cls, other):
+ return cls.label == other.label
-RANKS = dict([(x, type(x, (Rank,), {'label': x}))
- for x in SYMBOLS.keys()])
+SYMBOLS = collections.OrderedDict([
-SUITS = dict([(x, type(x, (Suit,), {'label': x})) for x in SUIT_SET])
+ ('King', 'K'), ('Queen', 'Q'), ('Jack', 'J'),
+ ('Ten', '10'), ('Nine', '9'), ('Eight', '8'),
+ ('Seven', '7'), ('Six', '6'), ('Five', '5'),
+ ('Four', '4'), ('Three', '3'), ('Two', '2'),
+ ('Ace', 'A')])
+
+SUIT_LIST = ['Diamonds', 'Clubs', 'Hearts', 'Spades']
+
+RANKS = collections.OrderedDict([(x, type(x, (Rank,),
+ {'label': x, '__str__': to_str,
+ '__eq__': equal})) for x in SYMBOLS.keys()])
+SUITS = collections.OrderedDict([(x, type(x, (Suit,),
+ {'label': x, '__str__': to_str,
+ '__eq__': equal})) for x in SUIT_LIST])

  1. Използвам object.setattr() заради поведението на Rank.setattr(). Не намерих по-чисто решение, но може да пропускам нещо очевидно!?
  2. Ако събера целия блок на 71-ви ред стават над 70 символа.
  3. Без коментар за последните две точки