Check if binary representations of two numbers are anagram

from collections import Counter

def checkAnagram(num1,num2):

bin1 = bin(num1)[2:]

bin2 = bin(num2)[2:]

zeros = abs(len(bin1)-len(bin2))

if (len(bin1)>len(bin2)):

bin2 = zeros * '0' + bin2

else:

bin1 = zeros * '0' + bin1

dict1 = Counter(bin1)

dict2 = Counter(bin2)

if dict1 == dict2:

print('Yes')

else:

print('No')

if __name__ == "__main__":

num1 = 8

num2 = 4

checkAnagram(num1,num2)


Check if a given string is binary string or not

def check(string) :

p = set(string)

s = {'0', '1'}

if s == p or p == {'0'} or p == {'1'}:

print("Yes")

else :

print("No")


if __name__ == "__main__" :

string = "101010000111"

check(string)


Using itemgetter sort list of dictionaries by values

from operator import itemgetter

lis = [{ "name" : "Pooja", "age" : 22},

{ "name" : "Arjun", "age" : 20 },

{ "name" : "Nikhil" , "age" : 19 }]

print ("The list printed sorting by age:")

print (sorted(lis, key=itemgetter('age')))

print ("\r")

print ("The list printed sorting by age and name:")

print (sorted(lis, key=itemgetter('age', 'name')))

print ("\r")

print ("The list printed sorting by age in descending order:")

print (sorted(lis, key=itemgetter('age'),reverse = True))


Get Kth Column of Matrix using list comprehension

test_list = [[4, 5, 8], [8, 1, 20], [7, 12, 10]]

print("The original list is : " + str(test_list))

K = 2

res = [sub[K] for sub in test_list]

print("The Kth column of matrix is : " + str(res))


Words Frequency in String Shorthands

 # Using Counter() + split()

from collections import Counter

test_str = 'Python for engineers . Solution for python programs'

print("The original string is : " + str(test_str))

res = Counter(test_str.split())

print("The words frequency : " + str(dict(res)))