0

This is my code :

string_1 = input("Enter a string : ")
string_2 = input("Enter a second string : ")
a = sorted(string_1)
b = sorted(string_2)
print(a)
print(b)
if a in b and len(a) == len(b):
    print("these strings are anagram")
else:
    print("these strings are not anagram")  

For example :
Input:
Enter a string : mounir
Enter a second string : mounir
Output :

['i', 'm', 'n', 'o', 'r', 'u']
['i', 'm', 'n', 'o', 'r', 'u']
these strings are not anagram

momo123321
  • 147
  • 8
  • 3
    `a in b` isn't doing what you expect. It's checking to see if `a` is an *element* of `b`. But you can replace that entire test (including the length comparison) with `if a == b:`. – Tom Karzes Oct 19 '22 at 00:20
  • @TomKarzes But if the list a and the list b are equal, then shouldn't a be an element of b?, – momo123321 Oct 19 '22 at 00:22
  • `a` is a list, not one of the letters in the list `b`. – John Coleman Oct 19 '22 at 00:23
  • @JohnColeman ohh. so it doesnt make sense to python to ask if a list is in another list? the "in" operator only works for elements ? – momo123321 Oct 19 '22 at 00:25
  • @user20194358 In this case it doesn't make sense, although there are applications which involve lists of lists. – John Coleman Oct 19 '22 at 00:26
  • Everything can be an element. However, this kind of element testing considers the left-hand side as a *single* thing, even if that left-hand side happens to be a sequence (such as a list). For example `['i', 'm', 'n', 'o', 'r', 'u']` **would** be `in [['i', 'm', 'n', 'o', 'r', 'u']]` (notice the extra pair of brackets). – Karl Knechtel Oct 19 '22 at 00:40
  • As an aside, this test is not adequate. For example, the length of `'foo'` and `'off'` is the same, and every letter that can be found in `'foo'` can also be found in `'off'`, but they are not anagrams. Sorting the lists **doesn't help** with your approach; but once the lists have been sorted, it is simple to do a *correct* anagram check: simply check if the results are *equal*. See the linked duplicates for details. – Karl Knechtel Oct 19 '22 at 00:43
  • @user20194358 Consider the list `['a', 'b', 'c']`. It has three elements: `'a'`, `'b'`, and `'c'`. Period. The list itself, `['a', 'b', 'c']` is not one of those three, so it is not al element of itself. If you do `a in b`, all this is asking is whether `a` is an element of `b`. Just what you'd expect from the word `in`. This is simple, simple stuff. You should understand it in seconds. Do some tests. Start up Python, create a list, then test the `in` operator. – Tom Karzes Oct 19 '22 at 01:39

1 Answers1

-1

you should try with this one. I changed the condition.

string_1 = input("Enter a string : ")
string_2 = input("Enter a second string : ")
a = sorted(string_1)
b = sorted(string_2)
print(a)
print(b)
if sorted(a) == sorted(b):
print("these strings are anagram")
else:
    print("these strings are not anagram")