Frequency of a string in an array of strings | Python3 program to count number of times a string appears in an array of strings ; To store number of times a string is present . It is 0 is string is not present ; function to insert a string into the Trie ; calculation ascii value ; If the given node is not already present in the Trie than create the new node ; Returns count of occurrences of s in Trie ; inserting in Trie ; searching the strings in Trie ; Driver code
MAX_CHAR = 26 NEW_LINE class Trie : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . cnt = 0 NEW_LINE self . node = [ None for i in range ( MAX_CHAR ) ] NEW_LINE DEDENT DEDENT def insert ( root , s ) : NEW_LINE INDENT temp = root NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( not root . node [ index ] ) : NEW_LINE INDENT root . node [ index ] = Trie ( ) NEW_LINE DEDENT root = root . node [ index ] NEW_LINE DEDENT root . cnt += 1 NEW_LINE return temp NEW_LINE DEDENT def search ( root , s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( not root . node [ index ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT root = root . node [ index ] NEW_LINE DEDENT return root . cnt NEW_LINE DEDENT def answerQueries ( arr , n , q , m ) : NEW_LINE INDENT root = Trie ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT root = insert ( root , arr [ i ] ) NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT print ( search ( root , q [ i ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " aba " , " baba " , " aba " , " xzxb " ] NEW_LINE n = len ( arr ) NEW_LINE q = [ " aba " , " xzxb " , " ab " ] NEW_LINE m = len ( q ) NEW_LINE answerQueries ( arr , n , q , m ) NEW_LINE DEDENT