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
Java Code for Anagram
static void anagram(String s1,String s2){
if(s1.length()!=s2.length()){
System.out.println("not anagram");
return;
}
else{
int []arr=new int[256];
int size=s1.length();
for(int i=0;i<size;i++){
arr[s1.charAt(i)]++;
arr[s2.charAt(i)]--;
}
for(int i=0;i<256;i++){
if(arr[i]!=0){
System.out.println("not anagram");
return;
}
}
System.out.println("anagram");
}
}
Not sure if it was proposed up there, but I went with:
def is_anagram(a, b):
return sorted(a.lower()) == sorted(b.lower())
To check if two strings are anagrams of each other using dictionaries: Note : Even Number, special characters can be used as an input
def anagram(s):
string_list = []
for ch in s.lower():
string_list.append(ch)
string_dict = {}
for ch in string_list:
if ch not in string_dict:
string_dict[ch] = 1
else:
string_dict[ch] = string_dict[ch] + 1
return string_dict
s1 = "master"
s2 = "stream"
a = anagram(s1)
b = anagram(s2)
if a == b:
print "Anagram"
else:
print "Not Anagram"
Here's one typical assignment solution:
def anagram(s1, s2):
""" (str, str) -> bool
Return True if s1 and s2 are anagrams
>>> anagram(s1, s2)
True
"""
s1 = s1.replace(" ", "")
s2 = s2.replace(" ", "")
s1_new = list(s1)
s2_new = list(s2)
if len(s1_new) == len(s2_new):
dupe_found = True
while dupe_found:
dupe_found = False
for i in s1_new:
for j in s2_new:
if i == j:
s1_new.remove(i)
s2_new.remove(j)
dupe_found = True
break
break
return s1_new == s2_new
str1="abcd"
str2="bcad"
word1=[]
word2=[]
for x in range(len(str1)):
word1.append(str1[x])
for x in range(len(str2)):
word2.append(str2[x])
if(len(word1)==len(word2)):
for letter in word1:
if letter in word2:
word2.remove(letter)
if len(word2)==0:
print "anagram"
else:
print "not anagram"
def is_anagram(w1, w2):
w1, w2 = list(w1.upper()), list(w2.upper())
w2.sort()
w1.sort()
return w1 == w2