Open In App

Python Dictionary | Check if binary representations of two numbers are anagram

Last Updated : 30 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two numbers you are required to check whether they are anagrams of each other or not in binary representation.

Examples:

Input : a = 8, b = 4 
Output : Yes
Binary representations of both
numbers have same 0s and 1s.

Input : a = 4, b = 5
Output : No

Check if binary representations of two numbers

We have existing solution for this problem please refer Check if binary representations of two numbers are anagram link. We can solve this problem quickly in python using Counter(iterable) method and Dictionary Comparison. Approach is simple,

  1. Convert both number into it’s binary using bin() function.
  2. Since binary representation of both numbers could differ in length so we will append zeros in start of shorter string to make both string of equal length. ie.; append zeros = abs(len(bin1)-len(bin2)).
  3. Convert both output string containing 0 and 1 returned by bin function into dictionary using Counter() function, having 0 and 1 keys and their count as value. Compare both dictionaries, if value of 0’s and 1’s in both dictionaries are equal then binary representations of two numbers are anagram otherwise not.

Python3




# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
 
def checkAnagram(num1,num2):
 
    # convert numbers into in binary
    # and remove first two characters of
    # output string because bin function
    # '0b' as prefix in output string
    bin1 = bin(num1)[2:]
    bin2 = bin(num2)[2:]
 
    # append zeros in shorter string
    zeros = abs(len(bin1)-len(bin2))
    if (len(bin1)>len(bin2)):
         bin2 = zeros * '0' + bin2
    else:
         bin1 = zeros * '0' + bin1
 
    # convert binary representations
    # into dictionary
    dict1 = Counter(bin1)
    dict2 = Counter(bin2)
 
    # compare both dictionaries
    if dict1 == dict2:
         print('Yes')
    else:
         print('No')
 
# Driver program
if __name__ == "__main__":
    num1 = 8
    num2 = 4
    checkAnagram(num1,num2)
    


Output:

Yes

Check if binary representations of two numbers are Using zfill

This approach checks if the binary representations of two given numbers are anagrams or not. It first converts the numbers to their binary form and pads zeros to make it of length 32. It then counts the occurrences of 0s and 1s in each binary representation using two separate counters. Finally, it compares the counts of 0s and 1s for both numbers and returns “Yes” if they are equal, otherwise “No”.

Algorithm

1.  Convert both input integers into their binary representation using bin() function.
2. Fill each binary string with zeros to the left, so that they all have length of 32 bits, using zfill() method.
3. For each binary string, count the frequency of 0s and 1s and store them in count_a and count_b lists.
4. Check if the two lists are equal.
5. If the two lists are equal, return “Yes”, else return “No”.

Python3




def is_anagram_binary(a, b):
    bin_a = bin(a)[2:].zfill(32)
    bin_b = bin(b)[2:].zfill(32)
    count_a = [0, 0]
    count_b = [0, 0]
    for i in range(32):
        if bin_a[i] == '0':
            count_a[0] += 1
        else:
            count_a[1] += 1
        if bin_b[i] == '0':
            count_b[0] += 1
        else:
            count_b[1] += 1
    if count_a == count_b:
        return "Yes"
    else:
        return "No"
 
a = 8
b = 4 
print( is_anagram_binary(8, 4)) # Output: True


Output

Yes

Time complexity of this code is O(1) since the length of the binary representation is constant. 

Auxiliary Space is also O(1) since the count lists are of constant size.



Similar Reads

Python Program to Check if Two Strings are Anagram
Question: Given two strings s1 and s2, check if both the strings are anagrams of each other. Examples: Input : s1 = "listen" s2 = "silent" Output : The strings are anagrams. Input : s1 = "dad" s2 = "bad" Output : The strings aren't anagrams.Solution:Method #1 : Using sorted() function Python provides a inbuilt function sorted() which does not modif
5 min read
Using Counter() in Python to find minimum character removal to make two strings anagram
Given two strings in lowercase, the task is to make them Anagram. The only allowed operation is to remove a character from any string. Find minimum number of characters to be deleted to make both the strings anagram? If two strings contains same data set in any order then strings are called Anagrams. Examples: Input : str1 = "bcadeh" str2 = "hea" O
3 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Modify array by removing characters from their Hexadecimal representations which are present in a given string
Given an array arr[] of size N and a string S, the task is to modify given array by removing all characters from their hexadecimal representations that are present in S and then replacing the equivalent decimal element back into the array. Examples: Input: arr[] = {74, 91, 31, 122}, S = "1AB"Output: {4, 5, 15, 7}Explanation: 74 -> (4A)16 -> (
10 min read
Python Counter to find the size of largest subset of anagram words
Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input: ant magenta magnate tan
5 min read
Anagram checking in Python using collections.Counter()
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Examples: Input : str1 = “abcd”, str2 = “dabc” Output : True Input : str1 = “abcf”, str
2 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Convert String Dictionary to Dictionary Python
Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of the dictionary, in string format to a dictionary. Let's discuss certain ways in which this can be done. Convert String Dictionary to Dictionary Using json.loads() This task ca
6 min read
Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
three90RightbarBannerImg