The assignment is to write a program that accepts two groups of words from the user and then prints a \"True\" statement if the two are anagrams (or at least if all the lett
def anagram(a,b):
x=[]
y=[]
for i in a:
if i!=' ': # This will ignore the spaces in the sentence
x+=[i] # Adds only letters into a list and ignore the spaces
for i in b:
if i!=' ':
y+=[i]
if len(x)==len(y): # if length of two lists are not same, They are not anagrams anyway. So it directly returns False.
for i in range(len(x)):
for j in range(len(y)):
if x[i].lower()==y[j].lower():
y.pop(j) # If the letter matched between first and second list, that letter is poped from that list.
break
return len(y)==0 # If the given sentences are anagrams, all the letters are poped out from the second list and function returns True(as the lenght of the second list is 0. If not, function will return False.
return False
anagram(a,b)
Here's a solution if you are adamant on using Python dictionary and you can't use functional programming:
Create a dictionary using comprehension and compare the dictionaries of the two word with a simple ==
operator.
def isanagram2(wrd1, wrd2):
wrd1_dict = {k: 0 for k in wrd1}
wrd2_dict = {k: 0 for k in wrd2}
for c1, c2 in zip(wrd1, wrd2):
wrd1_dict[c1] += 1
wrd2_dict[c2] += 1
if wrd1_dict == wrd2_dict:
return True
return False
I think we can get this like this
s1 = "listen"
s2 = "silent"
s1=list(s1);s1.sort()
s2 = list(s2);s2.sort()
if s1 == s2:
print ("Given Strings are Anagram")
else:
print ("Given String are not anagrams")
Explanation: In the code below, we can answer two questions: 1) whether or not two strings are anagrams,2) If w2 is an anagram of a sub-sequence of w1. We use O(1) space (constant) and O(n) time. The dictionary d0 can be expanded to include any characters and we remain within O(1) space bound.
def anagrams(w1,w2):
d0={chr(i):0 for i in range(ord('a'),ord('z'))}
for char in w1:
d0[char]+=1
for char in w2:
if d0[char]==0:
return False
else:
d0[char]-=1
return sum([d0[x] for x in d0])==0 #return True (for subseqence anagram)
I think the shortest way can be:
fstr=input("enter first string:")
sstr=input("enter second string:")
if(fstr==sstr[::-1]):
print("it's anagram")
Just another solution without using sort:
s1 = "aaabbbccc"
s2 = "abcabcabc"
def are_anagram1(s1, s2):
return [False, True][sum([ord(x) for x in s1]) == sum([ord(x) for x in s2])]
print are_anagram1(s1,s2)
NB: this works only for alphabet not numerals