Efficiently check if an element occurs at least n times in a list

后端 未结 7 2197
南旧
南旧 2020-12-07 00:23

How to best write a Python function (check_list) to efficiently test if an element (x) occurs at least n times in a list (l

7条回答
  •  情深已故
    2020-12-07 00:59

    This shows another way of doing it.

    1. Sort the list.
    2. Find the index of the first occurrence of the item.
    3. Increase the index by one less than the number of times the item must occur. (n - 1)
    4. Find if the element at that index is the same as the item you want to find.

      def check_list(l, x, n):
          _l = sorted(l)
          try:
              index_1 = _l.index(x)
              return _l[index_1 + n - 1] == x
          except IndexError:
              return False
      

提交回复
热议问题