Showing posts with label Dictionary. Show all posts
Showing posts with label Dictionary. Show all posts

Counter to find the size of largest subset of anagram words

from collections import Counter

def maxAnagramSize(input):

input = input.split(" ")

for i in range(0,len(input)):

input[i]=''.join(sorted(input[i]))

freqDict = Counter(input)

print (max(freqDict.values()))

if __name__ == "__main__":

input = 'ant magenta magnate tan gnamate'

maxAnagramSize(input)


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)


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))


Possible Words using given characters

def charCount(word):

dict = {}

for i in word:

dict[i] = dict.get(i, 0) + 1

return dict

def possible_words(lwords, charSet):

for word in lwords:

flag = 1

chars = charCount(word)

for key in chars:

if key not in charSet:

flag = 0

else:

if charSet.count(key) != chars[key]:

flag = 0

if flag == 1:

print(word)

if __name__ == "__main__":

input = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run']

charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l']

possible_words(input, charSet)


Printing anagrams together using List and Dictionary

def allAnagram(input):

dict = {}

for strVal in input:

key = ''.join(sorted(strVal))

if key in dict.keys():

dict[key].append(strVal)

else:

dict[key] = []

dict[key].append(strVal)

output = ""

for key,value in dict.items():

output = output + ' '.join(value) + ' '

return output

if __name__ == "__main__":

input=['cat', 'dog', 'tac', 'god', 'act']

print (allAnagram(input))


Remove all duplicates words from a given sentence

from collections import Counter

def remov_duplicates(input):

input = input.split(" ")

for i in range(0, len(input)):

input[i] = "".join(input[i])

Uniq = Counter(input)

s = " ".join(Uniq.keys())

print (s)

if __name__ == "__main__":

input = 'Python is great and Java is also great'

remov_duplicates(input)


New Dictionary Creation and updation

student ={'john':50,'Tom':60,'Nina':82}
print 'First Time:',student
newstudent=student
print 'First Time:',newstudent
newstudent['Tom']=45
print 'Second Time:',newstudent
print 'Second Time:',student

online compiler used  https://repl.it/languages/python










Manipulation the Dictionary

d={10: 'iprg' , 22: 'Nan', 33:'Kool',8: 'Jool','y': 89,'tt':'toy',7:90 }
for i in d:                                
  print i,d[i]    # printing all the values in Dictionary          
print '\n'
print d[8]  #printing values of the individual keys
print '\n'
print d['y']  #printing values of the individual keys
print '\n'
print d[7]  #printing values of the individual keys
print '\n'
d[33]='hello world'  #updating the key 33 with new value
d[22]='pythonforengineers'   #updating the key 22 with new value
for i in d:                                
  print i,d[i]    # printing all the updated values in Dictionary    
del d[10]     # deleting key:value pair using key value -> 10
print'\n Dictionary after deleting a value:\n', d
d.clear()   #clearing all values
print '\n Dictionary after clearing all values:', d
del d   # Removing the Dictionary
try:
  print d
except:
  print 'Some error has occurred'
 

Creating a dictionary and traversing

d={10: 'iprg' , 22: 'Nan', 33:'Kool',8: 'Jool' } # Creating a dictionary with key: value pair

for i in d:                                     # Here key and the vaule can be any type.
  print i,d[i]                                  # Accessing elements in the dictionary

# Order in which they display is also different in output

print d.keys()  # print all keys in a dictionary

print d.values()  # print all values in a dictionary