试图在有序列表中查找重复项

时间:2018-02-16 18:26:05

标签: python-3.x

所以我的程序功能是将提供的数字添加到有序列表中,然后搜索重复项。我有一个函数找到我问过的数字的副本,我知道它是重复的。我试图让重复的函数读取列表,并将重复项附加到一个名为see的新列表。

class Node:
   def __init__(self,initdata):
       self.data = initdata
       self.next = None
   def getData(self):
       return self.data
   def getNext(self):
       return self.next
   def setNext(self,newnext):
       self.next = newnext

class OrderedList:
    def __init__(self):
        self.head = None

    def add(self, item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop: 
           if current.getData() > item:
            stop = True
           else:
               previous = current
               current = current.getNext()

        temp = Node(item)
        if previous == None:
            temp.setNext(self.head)
            self.head = temp
        else:
            temp.setNext (current)
            previous.setNext(temp)

   def prntlist(self):
       prnt = self.head
       while prnt != None:
          print(prnt.data, end=" ")
          prnt = prnt.next
       print()

   def duplic (self):
       currnt = self.head
       seen = set()
       uniq = []
       for i in range(int(currnt.data)):
           if i not in seen:
              uniq.append(i)
              seen.add(i)
       print (seen)


    def count(self, item):# function to count the value
        count = 0
        ptr = self.head
        while ptr != None:
          if (ptr.data == item):
              count += 1
          ptr = ptr.next
        return count

mylist = OrderedList()
mylist.add(23)
mylist.add(23)
mylist.add(10)
mylist.add(14)
mylist.add(5)
mylist.add(31)
mylist.add(35)
mylist.add(37)
mylist.add(26)
mylist.add(23)
mylist.add(29)
mylist.add(18)
mylist.add(2)
mylist.add(25)
mylist.prntlist()



print('Count of 23 in list: ', mylist.count(23))
print('Duplicates in list: ', mylist.duplic())

我想打印: 我的列表 列表中的23个:3 列表中的重复:{23,23}

1 个答案:

答案 0 :(得分:0)

您可能需要在问题中更清楚..

据我所知,你可以这样写函数:

def duplic (self):
       currnt = self.head
       seen = set()
       for i in currnt.data:
           if currnt.data.count(i)>1:
               seen.add(i)
       print (seen)

uniq似乎毫无用处。并且,set对象不能包含两个相同的元素,因此您不能拥有{23,23}。 (你可以写这个,但最终会产生{23}