I am trying to write a python code to check if two strings are anagrams of each other or not :
s1= input("enter 1st word or phrase: ")
s2= input("Enter your 2nd word or phrase: ")
s1=s1.lower()
s2=s2.lower()
if len(s1) != len(s2):
print("Not Anagrams")
else:
for x in s1:
if s1.count(x) != s2.count(x):
print("Not Anagrams")
break
else:
print("Anagrams")
This code is working fine for now , for example for strings like : listen ; silent or medical ;decimal or State;taSte
but it does not work for strings like : snooze alarms ; alas, no more Z's
Could you help me fix this code so that it also works for scenarios like this ?
@ric @TM oh I see. I didnt know it comes like that for you guys and I am also not sure if this is by design.
Let's see if @TudorRaduta can help or provide an info on the same.
This issue was reported a few weeks ago. For some reason, a few of the boards are using a different template for replies. The vendor has identified a solution, and it’s now pending implementation by our product manager, @Deanna .
Hi,
I do not master Python programming enough to provide a working code.
But here is the logic, I will use:
Just compare the two strings, non alphabetic characters removed, all lowercased and sorted by character. That will remove the need for a loop.
Regards,
Tshimanga
@TM your logic is clean and workable. But I am sure with this clarity and approach you can easily write the code if you want. Thanks for your inputs.
Here we're, in Perl
#!/usr/bin/perl
($s1, $s2) = @_
if (join("", sort(split(//, lc($s1) =~ s/[^a-z]//gr))) eq join("", sort(split(//, lc($s2) =~ s/[^a-z]//gr))))
{
print "Anagrams\n";
}
else
{
print "Not Anagrams\n";
}
For bash, I did not find an easy and simple way to split the variable each character on its own line.
Thanks @TM for your inputs !
Red Hat
Learning Community
A collaborative learning environment, enabling open source skill development.