Search code examples
pythonstringenumerate

Count occurrences of Enum in a string


I am attempting to count the number of occurrences of an ENUM in a string value e.g.

class numbers(Enum): 
   one = 1
   two = 2

string = "121212123324"

string.count(str(numbers.one.value))

This just seems very unintuitive to convert the enum back to string - are there any quicker ways?


Solution

  • Your solution is good, you can see runtime of 5 approach in below:

    from timeit import timeit
    from collections import Counter
    from enum import Enum
    
    class numbers(Enum): 
        one = 1
        two = 2
        three = 3
        four = 4
    
    def approach1(products):
        return Counter(products)[str(numbers.one.value)]
    
    def approach2(products):
        return products.count(str(numbers.one.value))
    
    def approach3(products):
        lst = list(map(int, products))
        return lst.count(int(numbers.one.value))
    
    def approach4(products):
        cnt = Counter(products)
        return (cnt[str(numbers.one.value)] , str(numbers.two.value) , 
            cnt[str(numbers.three.value)] , str(numbers.four.value))
    
    def approach5(products):
        cnt_o = products.count(str(numbers.one.value))
        cnt_t = products.count(str(numbers.two.value))    
        cnt_h = products.count(str(numbers.three.value))
        cnt_f = products.count(str(numbers.four.value))
        return (cnt_o , cnt_t , cnt_h , cnt_f)
    
    
    funcs = approach1, approach2, approach3 , approach4, approach5
    products = "121212123324"*10000000
    
    
    for _ in range(3):
        for func in funcs:
            t = timeit(lambda: func(products), number=1)
            print('%.3f s ' % t, func.__name__)
        print()
    

    Output:

    6.279 s  approach1
    0.140 s  approach2
    17.172 s  approach3
    6.403 s  approach4
    0.491 s  approach5
    
    6.340 s  approach1
    0.139 s  approach2
    16.049 s  approach3
    6.559 s  approach4
    0.474 s  approach5
    
    6.245 s  approach1
    0.143 s  approach2
    15.876 s  approach3
    6.172 s  approach4
    0.475 s  approach5