Common Python Coding Interview Questions: Part 2
A breakdown of a common Python problem given in interviews
Write a function to check if two strings are anagrams* of each other…
*An anagram is a word formed by rearranging the letters of another word
def anagrams(string1, string2):
if sorted(string1) == sorted(string2):
print ("These strings ARE anagrams of each other.")
else:
print ("These strings ARE NOT anagrams of each other.")
Step 1: Declare the function
Since you are asked to write a function, it’s important to do so! Right away you should type ‘def’ and come up with an appropriate name for your function. Since the prompt tells you that you will be comparing two strings, be sure to include two arguments in your function declaration that will represent each string.
Step 2: Write your conditional statement
The key to solving this problem is figuring out how you can check if two strings have the exact same letters. The simplest way to do this is by using the sorted function, which, when used on a string, sorts the string in alphabetical order. If we run the sorted function on two strings that are indeed…