Решение на Тесте карти от Йосиф Цветков

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

Към профила на Йосиф Цветков

Резултати

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

Код

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['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']]
class Rank:
def __str__(self):
return self.__class__.__name__
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
def __str__(self):
return self.__class__.__name__
def __eq__(self, other):
return self.__class__ == other.__class__
RANKS = {rank: type(rank, (Rank,), {'symbol': symbol})
for rank, symbol in VALID_RANKS}
SUITS = {suit: type(suit, (Suit,), {'color': color})
for suit, color in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
self._rank = rank()
self._suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
@property
def rank(self):
return self._rank
@property
def suit(self):
return self._suit
class CardCollection:
def __init__(self, collection=[]):
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[5:12]])

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

................
----------------------------------------------------------------------
Ran 16 tests in 0.019s

OK

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

Йосиф обнови решението на 20.03.2014 01:29 (преди над 10 години)

+class Rank:
+ VALID_RANKS = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'}
+
+ def __init__(self, symbol):
+ if symbol in Rank.VALID_RANKS:
+ self.symbol = symbol
+ else:
+ print('Error - "{}" is not valid rank for card !!!'.format(symbol))
+
+ def __eq__(self, other):
+ return self.__class__ == other.__class__
+
+
+class Suit:
+ VALID_SUITS = {'red', 'black'}
+
+ def __init__(self, color):
+ if color in Suit.VALID_SUITS:
+ self.color = color
+ else:
+ print('Error - "{}" is not valid suit for card !!!'.format(color))
+
+ def __eq__(self, other):
+ return self.__class__ == other.__class__
+
+
+class Two(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '2')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Three(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '3')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Four(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '4')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Five(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '5')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Six(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '6')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Seven(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '7')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Eight(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '8')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Nine(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '9')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Ten(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, '10')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Jack(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, 'Jack')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Queen(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, 'Queen')
+
+ def __str__(self):
+ return self.symbol
+
+
+class King(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, 'King')
+
+ def __str__(self):
+ return self.symbol
+
+
+class Ace(Rank):
+
+ def __init__(self):
+ Rank.__init__(self, 'Ace')
+
+ def __str__(self):
+ return self.symbol
+
+
+RANKS = {'Two': Two, 'Three': Three, 'Four': Four, 'Five': Five, 'Six': Six,
+ 'Seven': Seven, 'Eight': Eight, 'Nine': Nine, 'Ten': Ten,
+ 'Jack': Jack, 'Queen': Queen, 'King': King, 'Ace': Ace}
+
+
+class Spades(Suit):
+
+ def __init__(self):
+ Suit.__init__(self, 'black')
+
+ def __str__(self):
+ return "Spades"
+
+
+class Clubs(Suit):
+
+ def __init__(self):
+ Suit.__init__(self, 'black')
+
+ def __str__(self):
+ return "Clubs"
+
+
+class Diamonds(Suit):
+
+ def __init__(self):
+ Suit.__init__(self, 'red')
+
+ def __str__(self):
+ return "Diamonds"
+
+
+class Hearts(Suit):
+
+ def __init__(self):
+ Suit.__init__(self, 'red')
+
+ def __str__(self):
+ return "Hearts"
+
+
+SUITS = {'Spades': Spades, 'Clubs': Clubs,
+ 'Diamonds': Diamonds, 'Hearts': Hearts}
+
+
+class Card:
+
+ def __init__(self, rank, suit):
+ self.rank = rank()
+ self.suit = suit()
+
+ def __str__(self):
+ return '{} of {}'.format(self.rank, self.suit) # ???
+
+ def __eq__(self, other):
+ return self.rank == other.rank and self.suit == other.suit
+
+
+class CardCollection:
+
+ def __init__(self, collection=None):
+ if collection == None:
+ self.collection = []
+ else:
+ self.collection = list(collection)
+
+ def __getitem__(self, key):
+ return self.collection[key]
+
+ def add(self, card):
+ self.collection.append(card)
+
+ def top_card(self):
+ return self.collection[len(self.collection) - 1]
+
+ def bottom_card(self):
+ return self.collection[0]
+
+ def draw(self, index):
+ return self.collection.pop(index)
+
+ def draw_from_top(self):
+ return self.collection.pop(len(self.collection) - 1)
+
+ def draw_from_bottom(self):
+ return self.collection.pop()
+
+ def index(self, card):
+ return self.collection.index(card)
+
+ def __len__(self):
+ return len(self.collection)
+
+
+def StandardDeck():
+ return [Card(i, j) for i in RANKS for j in SUITS]
+
+
+def BeloteDeck():
+ return [Card(i, j) for i in RANKS for j in SUITS if i.isalpha() or int(i) > 6]
+
+
+def SixtySixDeck():
+ return [Card(i, j) for i in RANKS for j in SUITS if i.isalpha() or int(i) > 8]

Не е нужно да валидираш каквото и да е. Ние сме фенове на патешкото типизиране.

Стандартните тестета имат стриктна подредба -- пусни си няколко пъти програмата и виж какво се случва с подредбата на картите ти в SixtySixDeck() например.

Йосиф обнови решението на 20.03.2014 16:55 (преди над 10 години)

+VALID_SUITS = [['Spades', 'black'], ['Hearts', 'red'],
+ ['Clubs', 'black'], ['Diamonds', 'red']]
+VALID_RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six',
+ 'Seven', 'Eight', 'Nine', 'Ten',
+ 'Jack', 'Queen', 'King']
+
+
class Rank:
- VALID_RANKS = {'2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace'}
def __init__(self, symbol):
- if symbol in Rank.VALID_RANKS:
- self.symbol = symbol
- else:
- print('Error - "{}" is not valid rank for card !!!'.format(symbol))
+ self.symbol = symbol
+ def __str__(self):
+ return self.symbol
+
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
- VALID_SUITS = {'red', 'black'}
def __init__(self, color):
- if color in Suit.VALID_SUITS:
- self.color = color
- else:
- print('Error - "{}" is not valid suit for card !!!'.format(color))
+ self.color = color
def __eq__(self, other):
return self.__class__ == other.__class__
-class Two(Rank):
+RANKS = {i: (type(i, (Rank,),
+ {'__init__':
+ (lambda x: Rank.__init__(x, x.__class__.__name__))}))
+ for i in VALID_RANKS}
- def __init__(self):
- Rank.__init__(self, '2')
- def __str__(self):
- return self.symbol
+SUITS = {i: (type(i, (Suit,), {'__init__': (lambda x: Suit.__init__(x, j)),
+ '__str__': (lambda x: x.__class__.__name__)}))
+ for i, j in VALID_SUITS}
-class Three(Rank):
-
- def __init__(self):
- Rank.__init__(self, '3')
-
- def __str__(self):
- return self.symbol
-
-
-class Four(Rank):
-
- def __init__(self):
- Rank.__init__(self, '4')
-
- def __str__(self):
- return self.symbol
-
-
-class Five(Rank):
-
- def __init__(self):
- Rank.__init__(self, '5')
-
- def __str__(self):
- return self.symbol
-
-
-class Six(Rank):
-
- def __init__(self):
- Rank.__init__(self, '6')
-
- def __str__(self):
- return self.symbol
-
-
-class Seven(Rank):
-
- def __init__(self):
- Rank.__init__(self, '7')
-
- def __str__(self):
- return self.symbol
-
-
-class Eight(Rank):
-
- def __init__(self):
- Rank.__init__(self, '8')
-
- def __str__(self):
- return self.symbol
-
-
-class Nine(Rank):
-
- def __init__(self):
- Rank.__init__(self, '9')
-
- def __str__(self):
- return self.symbol
-
-
-class Ten(Rank):
-
- def __init__(self):
- Rank.__init__(self, '10')
-
- def __str__(self):
- return self.symbol
-
-
-class Jack(Rank):
-
- def __init__(self):
- Rank.__init__(self, 'Jack')
-
- def __str__(self):
- return self.symbol
-
-
-class Queen(Rank):
-
- def __init__(self):
- Rank.__init__(self, 'Queen')
-
- def __str__(self):
- return self.symbol
-
-
-class King(Rank):
-
- def __init__(self):
- Rank.__init__(self, 'King')
-
- def __str__(self):
- return self.symbol
-
-
-class Ace(Rank):
-
- def __init__(self):
- Rank.__init__(self, 'Ace')
-
- def __str__(self):
- return self.symbol
-
-
-RANKS = {'Two': Two, 'Three': Three, 'Four': Four, 'Five': Five, 'Six': Six,
- 'Seven': Seven, 'Eight': Eight, 'Nine': Nine, 'Ten': Ten,
- 'Jack': Jack, 'Queen': Queen, 'King': King, 'Ace': Ace}
-
-
-class Spades(Suit):
-
- def __init__(self):
- Suit.__init__(self, 'black')
-
- def __str__(self):
- return "Spades"
-
-
-class Clubs(Suit):
-
- def __init__(self):
- Suit.__init__(self, 'black')
-
- def __str__(self):
- return "Clubs"
-
-
-class Diamonds(Suit):
-
- def __init__(self):
- Suit.__init__(self, 'red')
-
- def __str__(self):
- return "Diamonds"
-
-
-class Hearts(Suit):
-
- def __init__(self):
- Suit.__init__(self, 'red')
-
- def __str__(self):
- return "Hearts"
-
-
-SUITS = {'Spades': Spades, 'Clubs': Clubs,
- 'Diamonds': Diamonds, 'Hearts': Hearts}
-
-
class Card:
def __init__(self, rank, suit):
self.rank = rank()
self.suit = suit()
def __str__(self):
- return '{} of {}'.format(self.rank, self.suit) # ???
+ return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
class CardCollection:
def __init__(self, collection=None):
- if collection == None:
+ if collection is None:
self.collection = []
else:
self.collection = list(collection)
+ def __len__(self):
+ return len(self.collection)
+
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self.collection) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop(len(self.collection) - 1)
def draw_from_bottom(self):
return self.collection.pop()
def index(self, card):
return self.collection.index(card)
- def __len__(self):
- return len(self.collection)
-
def StandardDeck():
- return [Card(i, j) for i in RANKS for j in SUITS]
+ return [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
+ for i in VALID_RANKS]
def BeloteDeck():
- return [Card(i, j) for i in RANKS for j in SUITS if i.isalpha() or int(i) > 6]
+ full_deck = StandardDeck()
+ unnecessary_cards = [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
+ for i in VALID_RANKS[1:6]]
+ for i in unnecessary_cards:
+ full_deck.remove(i)
+ full_deck.reverse()
+ return CardCollection(full_deck)
def SixtySixDeck():
- return [Card(i, j) for i in RANKS for j in SUITS if i.isalpha() or int(i) > 8]
+ full_deck = StandardDeck()
+ unnecessary_cards = [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
+ for i in VALID_RANKS[1:8]]
+ for i in unnecessary_cards:
+ full_deck.remove(i)
+ full_deck.reverse()
+ return CardCollection(full_deck)

Йосиф обнови решението на 20.03.2014 17:06 (преди над 10 години)

VALID_SUITS = [['Spades', 'black'], ['Hearts', 'red'],
['Clubs', 'black'], ['Diamonds', 'red']]
VALID_RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six',
'Seven', 'Eight', 'Nine', 'Ten',
'Jack', 'Queen', 'King']
class Rank:
def __init__(self, symbol):
self.symbol = symbol
def __str__(self):
return self.symbol
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
def __init__(self, color):
self.color = color
def __eq__(self, other):
return self.__class__ == other.__class__
RANKS = {i: (type(i, (Rank,),
- {'__init__':
- (lambda x: Rank.__init__(x, x.__class__.__name__))}))
+ {'__init__': (lambda x: Rank.__init__(x, x.__class__.__name__))}))
for i in VALID_RANKS}
SUITS = {i: (type(i, (Suit,), {'__init__': (lambda x: Suit.__init__(x, j)),
'__str__': (lambda x: x.__class__.__name__)}))
for i, j in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
self.rank = rank()
self.suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
class CardCollection:
def __init__(self, collection=None):
if collection is None:
self.collection = []
else:
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self.collection) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop(len(self.collection) - 1)
def draw_from_bottom(self):
return self.collection.pop()
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
for i in VALID_RANKS]
def BeloteDeck():
- full_deck = StandardDeck()
- unnecessary_cards = [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
- for i in VALID_RANKS[1:6]]
- for i in unnecessary_cards:
- full_deck.remove(i)
- full_deck.reverse()
- return CardCollection(full_deck)
+ return CardCollection([Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
+ for i in VALID_RANKS
+ if i not in VALID_RANKS[1:6]])
def SixtySixDeck():
- full_deck = StandardDeck()
- unnecessary_cards = [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
+ return CardCollection([Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
- for i in VALID_RANKS[1:8]]
+ for i in VALID_RANKS
- for i in unnecessary_cards:
+ if i not in VALID_RANKS[1:8]])
- full_deck.remove(i)
- full_deck.reverse()
- return CardCollection(full_deck)

Иначе, да, не е в духа на задачата да напишеш всеки клас на отделен ред :).

Не е нужно да предефинираш конструктора и str на всеки отделен клас. Помисли как да го направиш в родителския клас. Възможно е всички класове за карти и бои да се различават само по един атрибут.

Йосиф обнови решението на 23.03.2014 00:35 (преди над 10 години)

-VALID_SUITS = [['Spades', 'black'], ['Hearts', 'red'],
- ['Clubs', 'black'], ['Diamonds', 'red']]
-VALID_RANKS = ['Ace', 'Two', 'Three', 'Four', 'Five', 'Six',
- 'Seven', 'Eight', 'Nine', 'Ten',
- 'Jack', 'Queen', 'King']
+VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
+ ['Hearts', 'red'], ['Spades', 'black']]
+VALID_RANKS = [['King', 'K'], ['Queen', 'Q'], ['Jack', 'J'], ['Ten', '10'],
+ ['Nine', '9'], ['Eight', '8'], ['Seven', '7'], ['Six', '6'],
+ ['Five', '5'], ['Four', '3'], ['Three', '3'], ['Two', '2'],
+ ['Ace', 'A']]
class Rank:
def __init__(self, symbol):
self.symbol = symbol
def __str__(self):
return self.symbol
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
def __init__(self, color):
self.color = color
def __eq__(self, other):
return self.__class__ == other.__class__
+ def __str__(self):
+ return self.color
-RANKS = {i: (type(i, (Rank,),
- {'__init__': (lambda x: Rank.__init__(x, x.__class__.__name__))}))
- for i in VALID_RANKS}
+RANKS = {i: (type(i, (Rank,), {'__init__': (lambda x: Rank.__init__(x, j)),
+ '__str__': (lambda x: x.__class__.__name__)}))
+ for i, j in VALID_RANKS}
+
SUITS = {i: (type(i, (Suit,), {'__init__': (lambda x: Suit.__init__(x, j)),
'__str__': (lambda x: x.__class__.__name__)}))
for i, j in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
- self.rank = rank()
- self.suit = suit()
+ self.__setattr__('rank', rank(), 0)
+ self.__setattr__('suit', suit(), 0)
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
+ def __setattr__(self, name, value, test):
+ if test == 0:
+ return object.__setattr__(self, name, value)
+ else:
+ raise AttributeError("This object is immutable !!!")
+
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
class CardCollection:
def __init__(self, collection=None):
if collection is None:
self.collection = []
else:
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
- return self.collection[len(self.collection) - 1]
+ return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
- return self.collection.pop(len(self.collection) - 1)
+ return self.collection.pop()
def draw_from_bottom(self):
- return self.collection.pop()
+ return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
- return [Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
- for i in VALID_RANKS]
+ return CardCollection([Card(RANKS[rank], SUITS[suit])
+ for suit, color in VALID_SUITS
+ for rank, symbol in VALID_RANKS])
def BeloteDeck():
- return CardCollection([Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
- for i in VALID_RANKS
- if i not in VALID_RANKS[1:6]])
+ return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
+ for suit, color in VALID_SUITS
+ for rank_and_symbol in VALID_RANKS
+ if rank_and_symbol not in VALID_RANKS[7:12]])
def SixtySixDeck():
- return CardCollection([Card(RANKS[i], SUITS[j]) for j, k in VALID_SUITS
- for i in VALID_RANKS
+ return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
- if i not in VALID_RANKS[1:8]])
+ for suit, color in VALID_SUITS
+ for rank_and_symbol in VALID_RANKS
+ if rank_and_symbol not in VALID_RANKS[5:12]])
+

Имам няколко въпроса относно този код:

1) защо ако напиша:

b = SUITS['Hearts']()
print(b.color) # изкарава "black"

но ако напиша:

a = RANKS['Ten']()
print(a.symbol) # изкарва "А"

Атрибюта "color", винаги получава символа на последния елемент във VALID_RANKS

2) за да бъде immutable класа Card, дефинирах функцията setattr() но не знам дали не е лоша практика да се прави това по начина покойто аз съм го направил. Направил съм го с флаг който тествам понеже бях забравил че класа трябва да е immutable и по този начин той става такъв с минимални модификации по кода. Много ли е зле ?

3) като цяло, кода функционира ли както се очаква тъй като минава тестовете които са качени във форума но съм малко параноик и имам предчувствие че нещо не е както трябва ?

Ако сте забелязали други неточности/грешки/... бих се радвал ако споделите.

Благодаря предварително !

Йосиф обнови решението на 24.03.2014 02:11 (преди над 10 години)

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['King', 'K'], ['Queen', 'Q'], ['Jack', 'J'], ['Ten', '10'],
['Nine', '9'], ['Eight', '8'], ['Seven', '7'], ['Six', '6'],
['Five', '5'], ['Four', '3'], ['Three', '3'], ['Two', '2'],
['Ace', 'A']]
class Rank:
def __init__(self, symbol):
self.symbol = symbol
def __str__(self):
return self.symbol
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
def __init__(self, color):
self.color = color
- def __eq__(self, other):
- return self.__class__ == other.__class__
-
def __str__(self):
return self.color
+ def __eq__(self, other):
+ return self.__class__ == other.__class__
-RANKS = {i: (type(i, (Rank,), {'__init__': (lambda x: Rank.__init__(x, j)),
- '__str__': (lambda x: x.__class__.__name__)}))
- for i, j in VALID_RANKS}
+RANKS = {rank: (type(rank, (Rank,), {'__init__': (lambda self:
+ Rank.__init__(self, symbol)),
+ '__str__': (lambda self:
+ self.__class__.__name__)}))
+ for rank, symbol in VALID_RANKS}
-SUITS = {i: (type(i, (Suit,), {'__init__': (lambda x: Suit.__init__(x, j)),
- '__str__': (lambda x: x.__class__.__name__)}))
- for i, j in VALID_SUITS}
+SUITS = {suit: (type(suit, (Suit,), {'__init__': (lambda self:
+ Suit.__init__(self, color)),
+ '__str__': (lambda self:
+ self.__class__.__name__)}))
+ for suit, color in VALID_SUITS}
+
class Card:
def __init__(self, rank, suit):
self.__setattr__('rank', rank(), 0)
self.__setattr__('suit', suit(), 0)
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __setattr__(self, name, value, test):
if test == 0:
return object.__setattr__(self, name, value)
else:
raise AttributeError("This object is immutable !!!")
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
class CardCollection:
def __init__(self, collection=None):
if collection is None:
self.collection = []
else:
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[5:12]])
-
  1. Явно си го фикснал, преди да ти отговорим :)
  2. Ок си го направил това да хвърляш exception, но е голяма глупост този аргумент test. Разкарай го
  3. Защо правиш това:
    def __init__(self, collection=None):
        if collection is None:
            self.collection = []
        else:
            self.collection = list(collection)
  1. Всъщност не, все още не съм го оправил и не мога да се усетя защо се омазва. A сега забелязах че и SUITS има същия проблем :(
  2. Имам променлива "test" за да мога да различавам присвояванията направени от конструктора с всички останали присвоявания и така да направя обекта immutable.
  3. Заради теста:

    def test_deck_add(self): deck = CardCollection()

Йосиф обнови решението на 24.03.2014 23:58 (преди над 10 години)

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['King', 'K'], ['Queen', 'Q'], ['Jack', 'J'], ['Ten', '10'],
['Nine', '9'], ['Eight', '8'], ['Seven', '7'], ['Six', '6'],
- ['Five', '5'], ['Four', '3'], ['Three', '3'], ['Two', '2'],
+ ['Five', '5'], ['Four', '4'], ['Three', '3'], ['Two', '2'],
['Ace', 'A']]
class Rank:
def __init__(self, symbol):
- self.symbol = symbol
+ self._symbol = symbol
def __str__(self):
- return self.symbol
+ return self._symbol
+ @property
+ def symbol(self):
+ return self._symbol
+
+ @symbol.setter
+ def symbol(self, new_symbol):
+ self._symbol = new_symbol
+
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
def __init__(self, color):
- self.color = color
+ self._color = color
def __str__(self):
- return self.color
+ return self._color
+ @property
+ def color(self):
+ return self._color
+
+ @color.setter
+ def color(self, new_color):
+ self._color = new_color
+
def __eq__(self, other):
return self.__class__ == other.__class__
-RANKS = {rank: (type(rank, (Rank,), {'__init__': (lambda self:
- Rank.__init__(self, symbol)),
- '__str__': (lambda self:
- self.__class__.__name__)}))
+RANKS = {rank: type(rank, (Rank,), {'__init__':
+ lambda x: Rank.__init__(x, symbol),
+ '__str__':
+ (lambda x: x.__class__.__name__),
+ 'symbol': symbol})
for rank, symbol in VALID_RANKS}
-SUITS = {suit: (type(suit, (Suit,), {'__init__': (lambda self:
- Suit.__init__(self, color)),
- '__str__': (lambda self:
- self.__class__.__name__)}))
+SUITS = {suit: type(suit, (Suit,), {'__init__':
+ lambda x: Suit.__init__(x, color),
+ '__str__':
+ (lambda x: x.__class__.__name__),
+ 'color': color})
for suit, color in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
- self.__setattr__('rank', rank(), 0)
- self.__setattr__('suit', suit(), 0)
+ self._rank = rank()
+ self._suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
- def __setattr__(self, name, value, test):
- if test == 0:
- return object.__setattr__(self, name, value)
- else:
- raise AttributeError("This object is immutable !!!")
-
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
+
+ @property
+ def rank(self):
+ return self._rank
+
+ @property
+ def suit(self):
+ return self._suit
class CardCollection:
def __init__(self, collection=None):
if collection is None:
self.collection = []
else:
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[5:12]])

Йосиф обнови решението на 25.03.2014 00:15 (преди над 10 години)

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['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']]
class Rank:
- def __init__(self, symbol):
- self._symbol = symbol
-
def __str__(self):
- return self._symbol
+ return self.__class__.__name__
- @property
- def symbol(self):
- return self._symbol
-
- @symbol.setter
- def symbol(self, new_symbol):
- self._symbol = new_symbol
-
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
- def __init__(self, color):
- self._color = color
-
def __str__(self):
- return self._color
+ return self.__class__.__name__
- @property
- def color(self):
- return self._color
-
- @color.setter
- def color(self, new_color):
- self._color = new_color
-
def __eq__(self, other):
return self.__class__ == other.__class__
-RANKS = {rank: type(rank, (Rank,), {'__init__':
- lambda x: Rank.__init__(x, symbol),
- '__str__':
- (lambda x: x.__class__.__name__),
- 'symbol': symbol})
+RANKS = {rank: type(rank, (Rank,), {'symbol': symbol})
for rank, symbol in VALID_RANKS}
-SUITS = {suit: type(suit, (Suit,), {'__init__':
- lambda x: Suit.__init__(x, color),
- '__str__':
- (lambda x: x.__class__.__name__),
- 'color': color})
+SUITS = {suit: type(suit, (Suit,), {'color': color})
for suit, color in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
self._rank = rank()
self._suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
@property
def rank(self):
return self._rank
@property
def suit(self):
return self._suit
class CardCollection:
def __init__(self, collection=None):
if collection is None:
self.collection = []
else:
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[5:12]])

След хилядите въпроси от моя страна, останах с впечатлението че трябва да се напише такъв код(или нещо подобно) но имам няколко въпроса относно това решение:

  1. Не е ли проблем че инстанциите от тип 'Rank' или 'Suit' нямат член данна 'symbol' или 'color' и че тяхните стрингови репрезентации(на обектите) ще са малко безмислени ?

  2. Ако се опитаме да променим някой от атрибютите на инстаниция от тип Card ще се "хвърли" exception което е добре, но ако се напише нещо като:

    card = Card(...)
    card.x = 123
    print(card.x) # 123
    

В този случай се променя обекта т.е. не е immutable. Това не е ли сериозен проблем ?

Йосиф обнови решението на 26.03.2014 16:30 (преди над 10 години)

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['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']]
class Rank:
+ def __init__(self, symbol):
+ self._symbol = symbol
+
def __str__(self):
- return self.__class__.__name__
+ return self._symbol
+ @property
+ def symbol(self):
+ return self._symbol
+
+ @symbol.setter
+ def symbol(self, new_symbol):
+ self._symbol = new_symbol
+
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
+ def __init__(self, color):
+ self._color = color
+
def __str__(self):
- return self.__class__.__name__
+ return self._color
+ @property
+ def color(self):
+ return self._color
+
+ @color.setter
+ def color(self, new_color):
+ self._color = new_color
+
def __eq__(self, other):
return self.__class__ == other.__class__
-RANKS = {rank: type(rank, (Rank,), {'symbol': symbol})
+RANKS = {rank: type(rank, (Rank,), {'__init__':
+ lambda x: Rank.__init__(x, symbol),
+ '__str__':
+ (lambda x: x.__class__.__name__),
+ 'symbol': symbol})
for rank, symbol in VALID_RANKS}
-SUITS = {suit: type(suit, (Suit,), {'color': color})
+SUITS = {suit: type(suit, (Suit,), {'__init__':
+ lambda x: Suit.__init__(x, color),
+ '__str__':
+ (lambda x: x.__class__.__name__),
+ 'color': color})
for suit, color in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
self._rank = rank()
self._suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
@property
def rank(self):
return self._rank
@property
def suit(self):
return self._suit
class CardCollection:
- def __init__(self, collection=None):
- if collection is None:
- self.collection = []
- else:
- self.collection = list(collection)
+ def __init__(self, collection=[]):
+ self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
-
-
-def SixtySixDeck():
- return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
- for suit, color in VALID_SUITS
- for rank_and_symbol in VALID_RANKS
- if rank_and_symbol not in VALID_RANKS[5:12]])

Йосиф обнови решението на 26.03.2014 16:32 (преди над 10 години)

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['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']]
class Rank:
def __init__(self, symbol):
self._symbol = symbol
def __str__(self):
return self._symbol
@property
def symbol(self):
return self._symbol
@symbol.setter
def symbol(self, new_symbol):
self._symbol = new_symbol
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
def __init__(self, color):
self._color = color
def __str__(self):
return self._color
@property
def color(self):
return self._color
@color.setter
def color(self, new_color):
self._color = new_color
def __eq__(self, other):
return self.__class__ == other.__class__
RANKS = {rank: type(rank, (Rank,), {'__init__':
lambda x: Rank.__init__(x, symbol),
'__str__':
(lambda x: x.__class__.__name__),
'symbol': symbol})
for rank, symbol in VALID_RANKS}
SUITS = {suit: type(suit, (Suit,), {'__init__':
lambda x: Suit.__init__(x, color),
'__str__':
(lambda x: x.__class__.__name__),
'color': color})
for suit, color in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
self._rank = rank()
self._suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
@property
def rank(self):
return self._rank
@property
def suit(self):
return self._suit
class CardCollection:
def __init__(self, collection=[]):
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
+
+
+def SixtySixDeck():
+ return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
+ for suit, color in VALID_SUITS
+ for rank_and_symbol in VALID_RANKS
+ if rank_and_symbol not in VALID_RANKS[5:12]])

Йосиф обнови решението на 26.03.2014 16:34 (преди над 10 години)

VALID_SUITS = [['Diamonds', 'red'], ['Clubs', 'black'],
['Hearts', 'red'], ['Spades', 'black']]
VALID_RANKS = [['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']]
class Rank:
- def __init__(self, symbol):
- self._symbol = symbol
-
def __str__(self):
- return self._symbol
+ return self.__class__.__name__
- @property
- def symbol(self):
- return self._symbol
-
- @symbol.setter
- def symbol(self, new_symbol):
- self._symbol = new_symbol
-
def __eq__(self, other):
return self.__class__ == other.__class__
class Suit:
- def __init__(self, color):
- self._color = color
-
def __str__(self):
- return self._color
+ return self.__class__.__name__
- @property
- def color(self):
- return self._color
-
- @color.setter
- def color(self, new_color):
- self._color = new_color
-
def __eq__(self, other):
return self.__class__ == other.__class__
-RANKS = {rank: type(rank, (Rank,), {'__init__':
- lambda x: Rank.__init__(x, symbol),
- '__str__':
- (lambda x: x.__class__.__name__),
- 'symbol': symbol})
+RANKS = {rank: type(rank, (Rank,), {'symbol': symbol})
for rank, symbol in VALID_RANKS}
-SUITS = {suit: type(suit, (Suit,), {'__init__':
- lambda x: Suit.__init__(x, color),
- '__str__':
- (lambda x: x.__class__.__name__),
- 'color': color})
+SUITS = {suit: type(suit, (Suit,), {'color': color})
for suit, color in VALID_SUITS}
class Card:
def __init__(self, rank, suit):
self._rank = rank()
self._suit = suit()
def __str__(self):
return '{} of {}'.format(self.rank, self.suit)
def __eq__(self, other):
return self.rank == other.rank and self.suit == other.suit
@property
def rank(self):
return self._rank
@property
def suit(self):
return self._suit
class CardCollection:
def __init__(self, collection=[]):
self.collection = list(collection)
def __len__(self):
return len(self.collection)
def __getitem__(self, key):
return self.collection[key]
def add(self, card):
self.collection.append(card)
def top_card(self):
return self.collection[len(self) - 1]
def bottom_card(self):
return self.collection[0]
def draw(self, index):
return self.collection.pop(index)
def draw_from_top(self):
return self.collection.pop()
def draw_from_bottom(self):
return self.collection.pop(0)
def index(self, card):
return self.collection.index(card)
def StandardDeck():
return CardCollection([Card(RANKS[rank], SUITS[suit])
for suit, color in VALID_SUITS
for rank, symbol in VALID_RANKS])
def BeloteDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
if rank_and_symbol not in VALID_RANKS[7:12]])
def SixtySixDeck():
return CardCollection([Card(RANKS[rank_and_symbol[0]], SUITS[suit])
for suit, color in VALID_SUITS
for rank_and_symbol in VALID_RANKS
- if rank_and_symbol not in VALID_RANKS[5:12]])
+ if rank_and_symbol not in VALID_RANKS[5:12]])