找到重复功能

时间:2014-03-01 21:21:28

标签: python function duplicates

我需要帮助在程序中加入find_duplicates函数。它需要遍历列表检查每个元素以查看它是否与目标匹配。跟踪找到的匹配项数并打印出句子摘要。

以下是我到目前为止编写的代码:

myList = [69, 1 , 99, 82, 17]

#Selection Sort Function 

def selection_sort_rev(aList):
    totalcomparisions = 0
    totalexchanges = 0
    p=0
    print("Original List:" , aList)
    print()
    n = len(aList)
    for end in range(n, 1, -1):      
        comparisions = 0
        exchanges = 1
        p= p + 1

#Determine Largest Value

        max_position = 0
        for i in range(1, end):
            comparisions = comparisions + 1
            if aList[i] < aList[max_position]:   
                max_position = i

#Passes and Exchanges 
        exchnages = exchanges + 1
        temp = aList [end - 1]       
        aList [end - 1] = aList [max_position]
        aList [max_position] = temp
        print ("Pass", p,":", "Comparsions:", comparisions, "\tExchanges:" , exchanges)
        print("\t", aList, "\n")
        totalcomparisions = totalcomparisions + comparisions
        totalexchanges = totalexchanges + exchanges

    print("\tTotal Comparisons:", totalcomparisions, "\tTotal Exchanges:", totalexchanges)
    return 

find_duplicates函数必须具有:

  • 输入参数:列表,目标(要查找的值)
  • 在列表中搜索目标并计算发生的次数
  • 返回值:无

我确信有更有效的方法可以做到这一点,但我是编程的初学者,我想知道如何以最简单的方式做到这一点。请帮助!!!

2 个答案:

答案 0 :(得分:0)

import collections

def find_duplicates(L, target):
    i_got_this_from_stackoverflow = collections.Counter(L)
    if target not in i_got_this_from_stackoverflow:
        print "target not found"
    else:
        print i_got_this_from_stackoverflow[target], "occurrences of the target were found"

答案 1 :(得分:0)

如果您希望提高编程技巧,这是一个很好的讨论。如果您只想获得问题的答案,请使用list.count()方法创建,以准确回答该问题:

>>> myList = [69, 1 , 99, 82, 17,  1, 82]
>>> myList.count(82)
2

此外,您的测试代码在列表中不包含任何重复项。这是一个必要的测试用例,但您还需要在至少一个列表中尝试使用重复项来测试代码,以便在它们存在时进行测试。

当你学习并开始掌握时,你可以通过学习各种组件的工作方式来节省大量的时间。但是,如果这是一项任务,请继续卡车!'