简体   繁体   English

计算(排序的)列表中给定项目的出现次数?

[英]Count the number of occurrences of a given item in a (sorted) list?

I'm asked to create a method that returns the number of occurrences of a given item in a list. 我被要求创建一种方法,该方法返回列表中给定项目的出现次数。 I know how to write code to find a specific item, but how can I code it to where it counts the number of occurrences of a random item. 我知道如何编写代码来查找特定项目,但是如何将其编码到计算随机项目出现次数的位置。

For example if I have a list [4, 6 4, 3, 6, 4, 9] and I type something like 例如,如果我有一个list [4, 6 4, 3, 6, 4, 9]并且我输入类似

s1.count(4) , it should return 3 or s1.count(6) should return 2 . s1.count(4) ,它应该return 3s1.count(6)应该return 2

I'm not allowed to use and built-in functions though. 我不允许使用和内置函数。

In a recent assignment, I was asked to count the number of occurrences that sub string "ou" appeared in a given string, and I coded it 在最近的一次作业中,我被要求计算sub string “ ou”出现在给定字符串中的出现次数,并对其进行了编码

if len(astr) < 2:
    return 0
else:
    return (astr[:2] == "ou")+ count_pattern(astr[1:])

Would something like this work?? 这样的工作会吗?

def count(self, item):
    num=0
    for i in self.s_list:
        if i in self.s_list:
            num[i] +=1
def __str__(self):
    return str(self.s_list)

If this list is already sorted, the "most efficient" method -- in terms of Big-O -- would be to perform a binary search with a count-forward/count-backward if the value was found. 如果此列表已经排序,则按照Big-O的“最有效”的方法将是执行二进制搜索,如果找到该值,则使用向前计数/向后计数。

However, for an unsorted list as in the example, then the only way to count the occurrences is to go through each item in turn (or sort it first ;-). 但是,对于示例中未排序的列表,唯一计算出现次数的方法是依次遍历每个项目(或首先对它进行排序;-)。 Here is some pseudo-code, note that it is simpler than the code presented in the original post (there is no if x in list or count[x] ): 这是一些伪代码,请注意,它比原始文章中介绍的代码更简单if x in listcount[x] ):

set count to 0
for each element in the list:
   if the element is what we are looking for:
      add one to count

Happy coding. 快乐的编码。

If I told you to count the number of fours in the following list, how would you do it? 如果我告诉您计算以下列表中的四位数, 将如何处理?

1 4 2 4 3 8 2 1 4 2 4 9 7 4

You would start by remembering no fours yet , and add 1 for each element that equals 4. To traverse a list, you can use a for statement . 您将首先no fours yet记得no fours yet ,并为等于4的每个元素加1。要遍历列表,可以使用for语句 Given an element of the list el , you can check whether it is four like this: 给定列表el的元素,您可以检查是否为四个,例如:

if el == 4:
  # TODO: Add 1 to the counter here

In response to your edit: 回应您的编辑:

You're currently testing if i in self.s_list: , which doesn't make any sense since i is an element of the list and therefore always present in it. 您目前正在测试if i in self.s_list: ,这没有任何意义,因为i是列表的元素,因此始终存在于列表中。

When adding to a number, you simply write num += 1 . 将数字相加时,只需编写num += 1 Brackets are only necessary if you want to access the values of a list or dictionary. 仅当您要访问列表或字典的值时,才需要使用方括号。

Also, don't forget to return num at the end of the function so that somebody calling it gets the result back. 另外,不要忘了在函数末尾return num ,以便有人调用它返回结果。

Actually the most efficient method in terms of Big-O would be O(log n). 实际上,就Big-O而言,最有效的方法是O(log n)。 @pst's method would result in O(log n + s) which could become linear if the array is made up of equal elements. @pst的方法将导致O(log n + s),如果数组由相等的元素组成,则O(log n + s)可能变为线性。

The way to achieve O(log n) would be to use 2 binary searches (which gives O(2log n), but we discard constants, so it is still O(log n)) that are modified to not have an equality test, therefore making all searches unsuccessful. 实现O(log n)的方法是使用2个二进制搜索(给出O(2log n),但是我们丢弃常量,因此仍然是O(log n))被修改为没有相等性测试,因此,所有搜索都将失败。 However, on an unsuccessful search (low > high) we return low. 但是,如果搜索失败(低>高),则返回低。

In the first search, if the middle is greater than your search term, recurse into the higher part of the array, else recurse into the lower part. 在第一个搜索中,如果中间值大于您的搜索词,则递归到数组的较高部分,否则递归到较低的部分。 In the second search, reverse the binary comparison. 在第二个搜索中,反转二进制比较。

The first search yields the right boundary of the equal element and the second search yields the left boundary. 第一次搜索产生等元素的右边界,第二次搜索产生左边界。 Simply subtract to get the amount of occurrences. 只需减去就可以得出事件的数量。 Based on algorithm described in Skiena. 基于Skiena中描述的算法。

This seems like a homework... anyways. 无论如何,这似乎是一项作业。 Try list.count(item) . 尝试list.count(item) That should do the job. 那应该做的。

Third or fourth element here: 这里的第三个或第四个元素:

http://docs.python.org/tutorial/datastructures.html http://docs.python.org/tutorial/datastructures.html

Edit: 编辑:

try something else like: 尝试其他类似的东西:

bukket = dict()
for elem in astr:
    if elem not in bukket.keys():
        bukket[elem] = 1
    else:
        bukket[elem] += 1

You can now get all the elements in the list with dict.keys() as list and the corresponding occurences with dict[key]. 现在,您可以使用dict.keys()作为列表获取列表中的所有元素,并使用dict [key]获得相应的出现次数。

So you can test it: 因此,您可以对其进行测试:

import random

l = []

for i in range(0,200):
    l.append(random.randint(0,20))

print l
l.sort()
print l

bukket = dict()
for elem in l:
    if elem not in bukket.keys():
        bukket[elem] = 1
    else:
        bukket[elem] += 1


print bukket

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算列表中每个项目的出现次数 - Count number of occurrences for each item in a list 计算没有list.count的列表中某项目的出现次数 - Count the number of occurrences of an item in a list without list.count 计算给定整数列表在另一整数列表中出现的总数 - Count total number of occurrences of given list of integers in another 计算数据流中给定字符串列表的出现次数 - Count number of occurrences of a given list of strings in a data stream 计算列表中每个唯一项的出现次数 - Count number of occurrences of each unique item in list of lists 给定一个项目,如何计算该项目在列表中的出现次数,如果不符合某些规定,则不打印该项目? - Given an item, how can I count the occurrences of said item in a list, and not print the item if it does not reach certain regulations? 将 re.findall 创建的列表拆分为单个单词,然后按出现次数降序计算每个单词的出现次数 - Split list created by re.findall to single words, then count occurrence of each word sorted descending by number of occurrences 计算元组列表出现的次数 - Count number of occurrences of list of tuples 需要计算if语句中给定字符串的出现次数 - need to count number of occurrences of given strings in an if statement 如何计算列表中大于给定数字的元素的出现次数? - How can I count occurrences of elements that are bigger than a given number in an list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM