cancel
Showing results for 
Search instead for 
Did you mean: 
Chetan_Tiwary_
Community Manager
Community Manager
  • 721 Views

Python coding error

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 

Chetan_Tiwary__0-1756231929765.png

Could you help me fix this code so that it also works for scenarios like this ?

 

Labels (3)
Tags (3)
16 Replies
Chetan_Tiwary_
Community Manager
Community Manager
  • 140 Views

@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.

TudorRaduta
Community Manager
Community Manager
  • 123 Views

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 .

TM
Starfighter Starfighter
Starfighter
  • 387 Views

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

Chetan_Tiwary_
Community Manager
Community Manager
  • 277 Views

@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. 

0 Kudos
TM
Starfighter Starfighter
Starfighter
  • 226 Views

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";
}

TM
Starfighter Starfighter
Starfighter
  • 212 Views

For bash, I did not find an easy and simple way to split the variable each character on its own line.

Chetan_Tiwary_
Community Manager
Community Manager
  • 172 Views

Thanks @TM for your inputs ! 

0 Kudos
Join the discussion
You must log in to join this conversation.