Python:将集合列表转换为集合

时间:2013-11-30 22:42:47

标签: python list set dfa

我正在开发一个涉及DFA的编程项目,我遇到了一个错误,我似乎无法弄清楚如何绕过。

在这段代码中:

from DFA import *

def DAWG():
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                'y', 'z']
    f = open('lexicontest.txt', 'r')
    dictionary = list(f)
    accepts = []
    for i in dictionary:
        if len(i) >= 3:
            accepts.append(i)
    D = from_word_list(accepts, alphabet)
    newStates = frozenset(D.mn_classes())

我收到此错误:

Traceback (most recent call last):
 File "...\DAWG.py", line 31, in <module>
DAWG()
  File "...\DAWG.py", line 19, in DAWG
newStates = frozenset(D.mn_classes())
TypeError: unhashable type: 'set'

这是因为方法mn_classes()返回一个元素为sets的列表。我正在寻找一种方法将此列表转换为一个集合,但我现在不能这样做,因为集合必须是可以清除的。如果有人能就如何将此列表转换为集合给我建议,我们将不胜感激。

我正在使用由Andrew Badr设计的DFA库找到herehere。这是mn_classes()方法的代码:

def mn_classes(self):
    """Returns a partition of self.states into Myhill-Nerode equivalence classes."""
    changed = True
    classes = []
    if self.accepts != []:
        classes.append(self.accepts)
    #nonaccepts = filter(lambda x: x not in self.accepts, self.states)
    nonaccepts = [x for x in self.states if x not in self.accepts]
    if nonaccepts != []:
        classes.append(str(nonaccepts))
    while changed:
        changed = False
        for cl in classes:
            local_change = False
            for alpha in self.alphabet:
                next_class = None
                new_class = []
                for state in cl:
                    next = self.delta(state, alpha)
                    if next_class == None:
                        for c in classes:
                            if next in c:
                                next_class = c
                    elif next not in next_class:
                        new_class.append(state)
                        changed = True
                        local_change = True
                if local_change == True:
                    old_class = []
                    for c in cl:
                        if c not in new_class:
                            old_class.append(c)
                    classes.remove(cl)
                    classes.append(old_class)
                    classes.append(new_class)
                    break
    return classes

1 个答案:

答案 0 :(得分:3)

您的mn_class代码看起来很可疑,尤其是classes.append(str(nonaccepts))似乎不是列表中的集合。 Followint部分也是可疑的:

if next_class == None:
    for c in classes:
        if next in c:
            next_class = c

回答你问的问题,“如果有人可以就如何将此列表转换为集合”modulo“mn_classes()给出建议,则返回一个列表,其元素为”你可以使用DAWG方法,即ie返回mn_classes中的frozensets列表:

return map(frosenset, classes)