Started by Allen ScottOct 31, 2021

# ClosedCount occurrences of Enum in a string

2 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWES SHARE

I am attempting to remember 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))

2 Replies

Murray Thomson replied 7 days ago0 likes0 dislikes

Your answer is good, you could see the runtime of 5 methods beneath:

`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`

Allen Scott replied 7 days ago0 likes0 dislikes

Thanks, now I got it.

This thread is closed by Allen Scott
Trending Technologies
15
Software39
DevOps45
Frontend Development24
Backend Development20
Data Center24
Sentry24
Terraform21
Ansible46
Docker28
Penetration Testing14
Kubernetes17
NGINX19
JenkinsX17