Python counter and dictionary intersection example

PythonServer Side ProgrammingProgramming

When it is required to demonstrate a counter and dictionary intersection, the Counter and dictionary can be used.

Below is the demonstration of the same −

Example

 Live Demo

from collections import Counter
def make_string(str_1,str_2):
   dict_one = Counter(str_1)
   dict_two = Counter(str_2)

   result = dict_one & dict_two

   return result == dict_one

string_1 = 'Hi Mark'
string_2 = 'how are yoU'
print("The first string is :")
print(string_1)
print("The second string is :")
print(string_2)
if (make_string(string_1,string_2)==True):
   print("It is possible")
else:
   print("It is not possible")

Output

The first string is :
Hi Mark
The second string is :
how are yoU
It is not possible

Explanation

  • The required packages are imported.

  • A method is defined, that takes two strings, and converts them into a counter.

  • It is then assigned to a dictionary.

  • Outside the dictionary, two strings are defined, and the method is called by passing these two strings.

  • The relevant output depending on whether the function returns ‘True’ or ‘False’ is shown on console.

raja
Published on 17-Apr-2021 12:45:45
Advertisements