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.")
Any two strings are anagrams of each other if the letters in both of the strings are the same. To sort the strings, we will use the sorted() function, which returns a sorted string. Then, we compare the sorted strings using the == operator, which returns True if the strings are anagrams of each other.
Two words are anagrams of each other if they contain the same number of characters and the same characters. You should only need to sort the characters in lexicographic order, and determine if all the characters in one string are equal to and in the same order as all of the characters in the other string.
lower() # check if length is same if(len(str1) == len(str2)): # sort the strings sorted_str1 = sorted(str1) sorted_str2 = sorted(str2) # if sorted char arrays are same if(sorted_str1 == sorted_str2): print(str1 + " and " + str2 + " are anagram.") else: print(str1 + " and " + str2 + " are not anagram.") else: print(str1 ...
Here's a solution if you are adamant on using Python dictionary and you can't use functional programming:
Create a dictionary using comprehension and compare the dictionaries of the two word with a simple ==
operator.
def isanagram2(wrd1, wrd2):
wrd1_dict = {k: 0 for k in wrd1}
wrd2_dict = {k: 0 for k in wrd2}
for c1, c2 in zip(wrd1, wrd2):
wrd1_dict[c1] += 1
wrd2_dict[c2] += 1
if wrd1_dict == wrd2_dict:
return True
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With