0

So I was solving a problem that wanted me to find out the number of times a sublist has occurred in a given list.

def count_sublist_occurrence(sublst, lst):

    """
    Input : non-empty list (sublst) and list (lst)
    Output: the number of times sublst occurs in lst
    For example:
    >>> count_sublist_occurrence([1, 2], [1, 2, 3, 1, 2, 3])
    2
    """

counter = 0

for i in range(len(lst)):
    if lst[i : len(sublst) + i] == sublst:
        counter += 1

return counter

It is not required to shorten the list but I decided to give it a try anyway. I tried to shorten it with list comprehension and I wrote something like this

counter for i in range(len(lst)) if lst[i : len(sublst) + 1] == sublst #counter += 1

This code is obviously wrong as I don't know how to increment the counter inside a list comprehension.

Is there a way for me to code this?

Bryan Hii
  • 129
  • 7
  • refer here:https://stackoverflow.com/questions/63438270/incrementing-counter-inside-list-comprehension/63438448 – gretal Nov 05 '21 at 07:41
  • Does this answer your question? [Python - keeping counter inside list comprehension](https://stackoverflow.com/questions/27778604/python-keeping-counter-inside-list-comprehension) – Antoine Nov 05 '21 at 07:42
  • 3
    How about using `sum`? `sum(lst[i:i+len(sublst)] == sublst for i in range(len(lst)))` or sth like that. – j1-lee Nov 05 '21 at 07:54
  • or you can also convert the lists to strings and use `.count`: `return ''.join(map(str, lst)).count(''.join(map(str, sublst)))` – Matiiss Nov 05 '21 at 08:10

0 Answers0