Checking strings against each other (Anagrams)
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 letters of one are present in the other) and a "False" statement if not.
Being very new to programming as a whole, I don't know how to move beyond just indexing a string and comparing all of the pieces of one to another. I stress that I am a beginner; I've read many of the other posts tagged with Python and Anagram, and they are uniformly above my head and reference things I have not been taught. So the simpler the better. Here is my non-working code so far:
s1 = input("Please enter a word:")
s2 = input("Please enter another word:")
for i in range(0, len(s1), 1):
if i in range (0, len(s2), 1):
print("The letters in your first word are present in your second word.")
Why not just sort the strings?
>>> sorted('anagram')
['a', 'a', 'a', 'g', 'm', 'n', 'r']
>>> sorted('nagaram')
['a', 'a', 'a', 'g', 'm', 'n', 'r']
>>> sorted('anagram') == sorted('nagaram')
True
You can use the magic Counter from collections library. From documentation:
It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values
So, you can initialize a Counter object with a string (a iterable) and compare with another Counter from a string
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break
out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True
and then setting that to false if you find a letter that doesn't match.
Some other tips:
for l in s1
will loop through string s1 giving you access to each letter in sequence asl
- you don't needrange
orlen
at allThe
if .. in
statement can help test whether a letter exists in a string, e.g.if letter in mystring:
is a valid statement and this could help you a lot, again not needingrange
orlen
You should avoid using numbers in variable names where possible - better would be
word_one
andword_two
, as an example
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"