SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
0.lists
Exercise:
Programming Excercises
Question:17 | ISBN:978013274719 | Edition: 6

Question

(Anagrams) Write a function that checks whether two words are anagrams. Two words are anagrams if they contain the same letters. For example, silent and listen are anagrams. The header of the function is: def isAnagram(s1, s2): (Hint: Obtain two lists for the two strings. Sort the lists and check if two lists are identical.) Write a test program that prompts the user to enter two strings and, if they are anagrams, displays is an anagram; otherwise, it displays is not an anagram.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Anagrams Program Code:

# Function to check whether two words are anagrams
def isAnagram(s1, s2):
    # Convert the strings to lowercase
    s1 = s1.lower()
    s2 = s2.lower()

    # Convert the strings to lists of characters
    s1_list = list(s1)
    s2_list = list(s2)

    # Sort the lists of characters
    s1_list.sort()
    s2_list.sort()

    # Check if the sorted lists are identical
    if s1_list == s2_list:
        return True
    else:
        return False

# Test program
def main():
    # Prompt the user to enter two strings
    wordOne = input("Enter the first word: ")
    wordTwo = input("Enter the second word: ")

    # Check if the strings are anagrams using the isAnagram function
    if isAnagram(wordOne, wordTwo):
        print("The words are anagrams.")
    else:
        print("The words are not anagrams.")

# Call the test program
main()

Executed Output 1:

Enter the first word: silent
Enter the second word: listen
The words are anagrams.

Executed Output 2:

Enter the first word: madam
Enter the second word: dear
The words are not anagrams.

 

 

 

0 0

Discussions

Post the discussion to improve the above solution.