Files
30-seconds-of-code/snippets/count_occurences.md
Rohit Tanwar 03d6c27f27 update scripts
2018-02-21 13:13:01 +05:30

520 B
Raw Blame History

count_occurences

Already implemented via list.count().

Counts the occurrences of a value in an list.

Uses the reduce functin from built-in module functools to increment a counter each time you encounter the specific value inside the list.

from functools import reduce


def count_occurences(arr, val):
    return reduce(
        (lambda x, y: x + 1 if y == val and type(y) == type(val) else x + 0),
        arr)
count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3