Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

An anagram is a word or phrase formed by rearranging the letters of another word

ID: 3783794 • Letter: A

Question

An anagram is a word or phrase formed by rearranging the letters of another word or phrase. Examples include: listen - silent cinema - ice man a telescope - to sec place Spaces obviously don't count when determining If two sets of words are anagrams. Case doesn't matter. Write a function called anagram. m that compares two strings and returns 1 (logical true) if they are anagrams, and 0 (logical false) if they are not. You can use any built-in functions you like (and no, there isn't a built-in anagram function.) Examples: >> r = anagram('dormitory', 'dirty room') r = anagram('yes', 'no') r = 0 anagram('dog', 'cat') r = 0 - anagram ('conversation', 'conservation') r =

Explanation / Answer

# Utility functions

def toList(string):

    tmp = []

    for i in string:

        tmp.append(i)

    return tmp

def toString(List):

    return ''.join(List)

# function to check whether two strings are anagram

# of each other

def areAnagram(str1, str2):

    # Get lengths of both strings

    n1 = len(str1)

    n2 = len(str2)

    # If lenght of both strings is not same, then

    # they cannot be anagram

    if n1 != n2:

        return 0

    # Sort both strings

    str1 = quickSort(str1, 0, n1 - 1)

    str2 = quickSort(str2, 0, n2 - 1)

    # Compare sorted strings

    for i in xrange(n1):

        if str1[i] != str2[i]:

            return 0

    return 1

# Following functions (exchange and partition are

# needed for quickSort)

def exchange(a, b):

    return b, a

def partition(A, si, ei):

    x = A[ei]

    i = si - 1

    for j in xrange(si, ei):

        if A[j] <= x:

            i+=1

            A[i], A[j] = exchange(A[i], A[j])

    A[i+1], A[ei] = exchange(A[i+1], A[ei])

    return i + 1

# Implementation of Quick Sort

# A[] --> Array to be sorted

# si --> Starting index

# ei --> Ending index

def quickSort(string, si, ei):

    A = toList(string)

    pi = 0

    if si < ei:

        pi = partition(A, si, ei)

        quickSort(A, si, pi-1)

        quickSort(A, pi+1, ei)

    return toString(A)

# Driver program to test the above function

str1 = "test"

str2 = "ttew"

if areAnagram(str1, str2):

    print "The two strings are anagram of each other"

else:

    print "The two strings are not anagram of each other"

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote