과제를 진행 중이며 큰 출발을 보였지만 계속하는 법을 모르고 조언 (답이 아닌)을 찾고 있습니다. 다음 클래스를 사용 :클래스를 사용하여 파이썬에서 카운터 함수를 사용하여 순차 검색을 만듭니다.
['hello': 3, 'world': 3]
목록의 각 단어가있는 단어에 대해 확인 : 나는 형식으로 출력을 생성하는 순차적 인 검색 프로그램을 작성하는 데 필요한하고
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)
새 목록을 만들고 단어가 없으면 단어가 카운터 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]
@ jbutler483 : erm, 그건 유효한 Python 구문이 아닙니다. – DSM
당신은'CounterNode'와'CounterList'를 구현해야합니까? 그들은 당신이 성취하려는 것을 과도하게 과장하고 있습니다. Python API에는 도구를 사용하여 달성하려는 목표를 훨씬 쉽게 달성 할 수 있습니다. – Dunes
@MartijnPieters, 죄송합니다. 태그를 추가/제거 할 때 많은 편집 작업이있었습니다. 무슨 일이 일어나고 있는지 알기가 꽤 어려웠습니다! 하지만 어쨌든, 분명히 이것을 구현하는 C#/java/최신 프로그래밍 언어로 작성 했으므로 이전에는 사용자를 (자신의 TIP처럼) 돕도록 고안된 "TIP"에 대해 사과해야합니다. 그래서 네, 잘못되었습니다,하지만 내 의견에 좋은 의도 -이 사이트에서 SOME과는 달리, 분명히했다. – jbutler483