Change language

Python counter and dictionary intersection example (create a string using delete and swap)

| | | | | |

Examples:

 Input: s1 = ABHISHEKsinGH: s2 = gfhfBHkooIHnfndSHEKsiAnG Output: Possible Input: s1 = Hello: s2 = dnaKfhelddf Output: Not Possible Input: s1 = GeekfogforGeeks: s1 = GeeksforGeeks: s2 = rtehes OutputGeks / pre> 

We have a solution to this problem, please refer to Create a string from another by removing and rearranging characters . We’ll quickly fix this problem in python. The approach is very simple,

  1. Convert both strings to a dictionary using intersection two dictionaries and compare the resulting output with the dictionary of the first line, if they are both equal, this means that otherwise you can convert the string.

# Python code to find if we can make the first line
# from the second, removing some characters from
# Second and rearrange the remaining characters.

from collections import Counter 

 

def makeString (str1, str2):

  

  # convert both lines to dictionaries

# the output will look like str1 = & quot; aabbcc & quot ;,

# dict1 = {& # 39 ; a & # 39 ;: 2, & # 39; b & # 39 ;: 2, & # 39; c & # 39 ;: 2}

# str2 = & # 39; abbbcc & # 39 ;, dict2 = {& # 39; a & # 39 ;: 1, & # 39; b & # 39 ;: 3, & # 39; c & # 39 ;: 2}

dict1 = Counter (str1)

dict2 = Counter (str2)

 

# take the intersection of two dictionaries

# output will be the result = {& # 39; a & # 39 ;: 1, & # 39; b & # 39 ;: 2, & # 39; c & # 39 ;: 2}

result = dict1 & amp; dict2

 

# compare the resulting dictionary with the first

  # compare the dictionary first compare keys

# and then compares their respective values ​​

return result = = dict1

 
# Driver program

if __ name__ = = "__ main__" :

str1 = ’ABHISHEKsinGH’

  str2 = ’ gfhfBHkooIHnfndSHEKsiAnG’

if (makeString (str1, str2) = = True ):

print ( "Possible" )

else :

print ( "Not Possible" )

 

Exit:

 Possible