Редактировать: я переработал весь пост и применил свой настоящий код, так как не смог указать на свою проблему.Спасибо всем, кто внес свой вклад, я надеюсь, что эта версия намного понятнее.
Моя цель - провести оценку большого числа по диапазонам покерных рук (например, у меня есть TT, а у вас AA, KK или AK).Для этого будет две входные строки «TT» и «AA, KK, AK».Эти строки разделяются на отдельные части («AA», «KK», «AK»), а затем используются в качестве ключей в моем тексте.Диктовка структурирована как объекты key: array ((card, card), ...).
Ниже приведен код для создания словаря и его записи в файл.Хотя словарь, созданный в верхней части, работает нормально, я не могу перенести его в файл для последующего импорта в другую программу без получения ошибок синтаксиса / имени.
from enum import Enum #need python 3.4
import operator
from random import shuffle
class CardValue(Enum): #name = value
A = 14
K = 13
Q = 12
J = 11
T = 10
N = 9
E = 8
S = 7
F = 6
def __str__(self):
if self.value > 9:
return "{}".format(self.name)
else:
return "{}".format(str(self.value))
class CardSuit(Enum):
c = 1
d = 2
h = 3
s = 4
def __str__(self):
return "{}".format(self.name)
class Card(tuple): #tuples are unchangable
def __new__(cls, value, suit): #new is immutable
assert isinstance(value, CardValue) #assert stops if following is False, isinstance checks if value is an item of CardValue
assert isinstance(suit, CardSuit)
return tuple.__new__(cls, (value, suit)) #return tuple should be similar to self.value, self.suit
@property #i need to understand this...
def value(self):
return self[0]
@property
def suit(self):
return self[1]
def __str__(self):
return "{}{}".format(str(self.value), self.suit.name)
def __repr__(self):
return(str(self))
def __setattr__(self, *ignored):
raise NotImplementedError
def __delattr__(self, *ignored):
raise NotImplementedError
class Deck: #holds all Card class Objects that are not drawn
def __init__(self): #creates a new shuffled Deck containing all Cards
self.cards = [
Card(value, suit) for value in CardValue for suit in CardSuit
]
#shuffle(self.cards)
def setCard(self, value, suit): #tries to deal a specific card from the deck
if Card(value, suit) in self.cards: #if successful returns the Card and removes from deck
self.removeCard(Card(value, suit).value, Card(value, suit).suit)
return Card(value, suit)
else:
print('not in deck')
def topCard(self):
cardone = self.cards.pop()
#self.removeCard(cardone.value, cardone.suit)
return(cardone)
def removeCard(self, value, suit): #tries to remove a specific Card from the deck // future dead cards
if Card(value, suit) in self.cards:
self.cards.remove(Card(value, suit))
else:
print('not in deck')
#this creates the dict in python
helpmemore = [] #temp array to store card combinations in
mylazydict = {} #dict to store arrays of card combinations in "AK" : []
for valueone in CardValue:
for valuetwo in CardValue:
for suitone in CardSuit:
for suittwo in CardSuit:
if valueone != valuetwo or suitone != suittwo: #no double cards
helpmemore.append((Card(valueone, suitone), Card(valuetwo, suittwo)))
mylazydict[str(valueone)+str(valuetwo)] = helpmemore
helpmemore = []
#this saves the dict to a file
dotdot = 0
input2_dict = open("input2_dict.py", "w")
input2_dict.write("input2_dict = {"+"\n")
for line in mylazydict:
input2_dict.write("\t"+"\""+line+"\" : "+str(mylazydict[line]))
if dotdot != len(mylazydict)-1:
input2_dict.write(",")
input2_dict.write("\n")
dotdot += 1
input2_dict.write("\t}")
input2_dict.close()
Ошибка:
File "input2_dict.py", line 7 "A9" : [(Ac, 9c), (Ac, 9d), (Ac, 9h), (Ac, 9s), (Ad, 9c), (Ad, 9d), (Ad, 9h), (Ad, 9s), (Ah, 9c), (Ah, 9d), (Ah, 9h), (Ah, 9s), (As, 9c), (As, 9d), (As, 9h), (As, 9s)], ^ SyntaxError: invalid syntax
Предполагаю, что из-за того, что 9 является целым числом и, просто взяв первую строку, я получаю ошибку имени:
Traceback (most recent call last): File "input2_dict.py", line 2, in <module> "AA" : [(Ac, Ad), (Ac, Ah), (Ac, As), (Ad, Ac), (Ad, Ah), (Ad, As), (Ah, Ac), (Ah, Ad), (Ah, As), (As, Ac), (As, Ad), (As, Ah)], NameError: name 'Ac' is not defined
Затем я хочу проверить, все ли карты из записи dict все еще находятся в Deck.cards