5 Questions for TYL on Strings(check if two string are anagrams)
Write a program to check
if two given strings are anagram or not
So an anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. (https://en.wikipedia.org/wiki/Anagram). It's an essential skill to win at scrabble too.
And there are several games you can play on your smart phones as well. I was pretty addicted to one... look for Anagram Solver.
So for example,
star
Anagram that make sense are : rats, arts, tsar (you get the point right?)
But this program is not so strict as to whether the resulting word is meaningful or not, so basically, we're checking if one word contains all the letters in another word.
A good starting point would be to check if the length of both the words are the same then proceed from there. We'll sort it, then check if each letter is the same.
You have to decide on a good sorting function to use. sorted is good, it is built in.
If you can't use built in functions, write your own sorting algorithms.
Program:
def checkanagram(w1, w2):
if len(word1) != len(word2):
return False
w1=sorted(w1)
w2=sorted(w2)
if w1==w2:
return True
return False
word1 = "star"
word2 = "tsar"
isanagram=checkanagram(word1, word2)
if isanagram:
print(word1," and ",word2,"are anagrams")
else:
print(word1," and ",word2,"are not anagrams")
output:
star and tsar are anagrams
star and tsas are not anagrams
So an anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. (https://en.wikipedia.org/wiki/Anagram). It's an essential skill to win at scrabble too.
And there are several games you can play on your smart phones as well. I was pretty addicted to one... look for Anagram Solver.
So for example,
star
Anagram that make sense are : rats, arts, tsar (you get the point right?)
But this program is not so strict as to whether the resulting word is meaningful or not, so basically, we're checking if one word contains all the letters in another word.
A good starting point would be to check if the length of both the words are the same then proceed from there. We'll sort it, then check if each letter is the same.
You have to decide on a good sorting function to use. sorted is good, it is built in.
If you can't use built in functions, write your own sorting algorithms.
Program:
def checkanagram(w1, w2):
if len(word1) != len(word2):
return False
w1=sorted(w1)
w2=sorted(w2)
if w1==w2:
return True
return False
word1 = "star"
word2 = "tsar"
isanagram=checkanagram(word1, word2)
if isanagram:
print(word1," and ",word2,"are anagrams")
else:
print(word1," and ",word2,"are not anagrams")
output:
star and tsar are anagrams
star and tsas are not anagrams
Comments
Post a Comment