Counting the number of occurrences of a string within a string

One way to do is to use std::string find function: #include <string> #include <iostream> int main() { int occurrences = 0; std::string::size_type pos = 0; std::string s = “FooBarFooBarFoo”; std::string target = “Foo”; while ((pos = s.find(target, pos )) != std::string::npos) { ++ occurrences; pos += target.length(); } std::cout << occurrences << std::endl; }

Fast way of counting non-zero bits in positive integer

For arbitrary-length integers, bin(n).count(“1”) is the fastest I could find in pure Python. I tried adapting Óscar’s and Adam’s solutions to process the integer in 64-bit and 32-bit chunks, respectively. Both were at least ten times slower than bin(n).count(“1”) (the 32-bit version took about half again as much time). On the other hand, gmpy popcount() … Read more

How to count the frequency of the elements in an unordered list?

In Python 2.7 (or newer), you can use collections.Counter: import collections a = [1,1,1,1,2,2,2,2,3,3,4,5,5] counter=collections.Counter(a) print(counter) # Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1}) print(counter.values()) # [4, 4, 2, 1, 2] print(counter.keys()) # [1, 2, 3, 4, 5] print(counter.most_common(3)) # [(1, 4), (2, 4), (3, 2)] print(dict(counter)) # {1: 4, 2: 4, … Read more