使用类在python中使用计数器函数创建顺序搜索

时间:2014-09-15 13:00:32

标签: python list class python-3.x counter

我正在完成一项任务,并且已经取得了一个重大开端但却不知道如何继续并且正在寻找一些建议(而不是答案)。使用以下类:

class CounterList:
    __n_comparisons__ = 0

    def __init__(self, data=None):
        if data is None:
            self.data = []
        else:
            self.data = data
        self.__n_accesses__ = 0

    def __getitem__(self, i):
        self.__n_accesses__ += 1
        return self.data[i]

    def __setitem__(self, i, item):
        self.__n_accesses__ += 1
        if type(item) != CounterNode:
            raise ValueError("Only Counter objects can be placed in a CounterList")
        else:
            self.data[i] = item

    def __delitem__(self, key):
        self.__n_accesses__ += 1
        del(self.data[key])

    def __len__(self):
        return len(self.data)

    def __repr__(self):
        return repr(self.data)

    def __contains__(self, item):
        raise TypeError("You can't use the 'in' keyword with a CounterList")

    def __eq__(self, other):
        self.__n_comparisons__ += 1
        return self.data == other

    def insert(self, index, item):
        if type(item) != CounterNode:
            raise ValueError("Only Counter objects can be added to a CounterList")
        else:
            self.data.insert(index, item)

    def index(self, a=None):
        raise TypeError("You can't do that with a CounterList")

    def append(self, item):
        if type(item) != CounterNode:
            raise ValueError("Only Counter objects can be added to a CounterList")
        else:
            self.data.append(item)

    def get_accesses(self):
        return self.__n_accesses__

    @classmethod
    def get_comparisons(cls):
        return cls.__n_comparisons__

    @classmethod
    def reset_comparisons(cls):
        cls.__n_comparisons__ = 0

class MyString:
    def __init__(self, i):
        self.i = i

    def __eq__(self, j):
        if type(j) != MyString:
            CounterList.__n_comparisons__ += 1
        return self.i == j

    def __le__(self, j):
        if type(j) != MyString:
            CounterList.__n_comparisons__ += 1
        return self.i <= j

    def __ne__(self, j):
        if type(j) != MyString:
            CounterList.__n_comparisons__ += 1
        return self.i != j

    def __lt__(self, j):
        if type(j) != MyString:
            CounterList.__n_comparisons__ += 1
        return self.i < j

    def __gt__(self, j):
        if type(j) != MyString:
            CounterList.__n_comparisons__ += 1
        return self.i > j

    def __ge__(self, j):
        if type(j) != MyString:
            CounterList.__n_comparisons__ += 1
        return self.i >= j

    def __repr__(self):
        return repr(self.i)

    def __getattr__(self, attr):
        '''All other behaviours use self.i'''
        return self.i.__getattr__(attr)

class CounterNode:
    def __init__(self, word, count=1):
        self.word = MyString(word)
        self.count = count

    def __repr__(self):
        return str(self.word) + ": " + str(self.count)

我需要编写一个顺序搜索程序,它以下列格式生成输出:

 ['hello': 3, 'world': 3]

如果对照新列表中的单词检查列表中的每个单词,并且如果单词不存在,则单词将添加到列表中,计数器为1,如果单词在列表中,则为程序应该只添加1个字数。

我到目前为止的代码是:

from classes_1 import CounterNode, CounterList

def word_counter_seq(words_list):
    my_list = CounterList()
    for new_word in words_list:
        i = 0
        q = 1
        if not my_list:
            new_counter = CounterNode (new_word, 1)
            my_list.append(new_counter)
        elif new_word == my_list[i].word:
            my_list[i].count +=1         
        elif len(my_list)>1:
            if new_word == my_list[i].word:
                my_list[i].count +=1
                i+=1
            elif new_word == my_list[q].word:
                my_list[q].count +=1
                q+=1
            else:
                new_counter = CounterNode (new_word, 1)
                my_list.append(new_counter)
        else:
            new_counter = CounterNode (new_word, 1)
            my_list.append(new_counter)

    return my_list

但是,对于现在的代码,它只返回原始列表中的前两个元素,并且返回任何后续项目,计数器为1,并作为单独的项目。例如:

['hello': 3, 'world': 3, 'test': 1, 'test': 1]

而不是:

['hello': 3, 'world': 3, 'test': 2]

1 个答案:

答案 0 :(得分:1)

根据你的作业要求你实现的类来判断,似乎是强迫你使用数组(尽管这里的dict可能会更好......)。以这种方式思考:

for each new_word in word_list:
    for each element in your_list:
         if new_word equals element:
              #do something
         else:
              #do something else

通过这样做,你消除了不必要的     如果没有列表: 检查并使您的代码更清洁,所以不会混淆自己。但是我注意到你的CounterList似乎测量了正在使用的访问次数。因此,如果您的任务需要的是最小化访问的解决方案,那么请考虑以下列表:

'test', 'book', 'whatever', 'test'

除非你这样做,否则你对比较相邻元素的想法是行不通的:

'book', 'test', 'test', 'whatever'

对不起,这个答案有点模糊,我不想为你破坏你的功课。