In this post, We will be going to see different ways to write a code in Python for counting number of letters in a word
Example:
Input: Word = "BioChemiThon" Output: B -> 1 i -> 2 o -> 2 C -> 1 h -> 2 e -> 1 m -> 1 T -> 1 n -> 1
Now, Let’s see the Codes:
Code 1: Using the concept of Dictionary.
# Given Word word = "BioChemiThon" # Take an empty dictionary dictionary = {} # loop through every letters of word for character in word: # check for letter is already # present in a dictionary or not # if present then increment count by 1 if character in dictionary: dictionary[character] += 1 # otherwise assign 1 to it else: dictionary[character] = 1 print("Given Word:", word) print("Count of each letters is:") # print letter and its count together for character, count in dictionary.items() : print(character,"->",count)
Output:
Given Word: BioChemiThon Count of number of each letters is: B -> 1 i -> 2 o -> 2 C -> 1 h -> 2 e -> 1 m -> 1 T -> 1 n -> 1
Code 2: Using the concept of Set and Dictionary.
# Given Word word = "BioChemiThon" # Set of characters of given word character_set = set(word) # Take an empty dictionary dictionary = {} # loop through every characters # of a character set for character in character_set: # Count of character in a word dictionary[character] = word.count(character) print("Given Word:", word) print("Count of each letters is:") # Print letter and its count together for character in dictionary : print(character, "->", dictionary[character])
Output:
Given Word: BioChemiThon Count of each letters is: T -> 1 n -> 1 m -> 1 B -> 1 i -> 2 e -> 1 h -> 2 C -> 1 o -> 2
Code 3: Using the concept of list-comprehension.
# Given Word word = "BioChemiThon" # Set of characters of given word character_set = set(word) # list-comprehension # list of tuples created character_count_list = [ (char, word.count(char)) for char in character_set] print("Given Word:", word) print("Count of each letters is:") # Print letter and its count together for char_count in character_count_list : print(char_count[0], "->", char_count[1])
Output:
Given Word: BioChemiThon Count of each letters is: T -> 1 n -> 1 m -> 1 B -> 1 i -> 2 e -> 1 h -> 2 C -> 1 o -> 2
Code 4: Using the concept of Counter class.
# from collections library import Counter # to this program from collections import Counter # Given Word word = "BioChemiThon" # Counter class will return counter object # contains key, value char_count_obj = Counter(word) print(type(char_count_obj)) print(char_count_obj) print("\nGiven Word:", word) print("Count of each letters is:") # Print letter and its count together for char in char_count_obj: print(char, "->", char_count_obj[char])
Output:
Counter({'i': 2, 'o': 2, 'h': 2, 'B': 1, 'C': 1, 'e': 1, 'm': 1, 'T': 1, 'n': 1}) Given Word: BioChemiThon Count of each letters is: B -> 1 i -> 2 o -> 2 C -> 1 h -> 2 e -> 1 m -> 1 T -> 1 n -> 1