Answer:
Here is the Python program:
def removeAnagram(array): #method to remove string from array of strings that is anagram of earlier string
s = set() #creates a set
output = [] #creates an output list
for string in array: # iterates through each string in array of strings
if ''.join(sorted(string)) not in s: #if sorted string of array is not in s
output.append(string) #append that string to output list
s.add(''.join(sorted(string))) #add that sorted string to s set
return sorted(output) #returns output list
array = ['code', 'doce', 'ecod', 'framer', 'frame'] #creates a list of words
print(removeAnagram(array)) #calls method to remove each string that is an anagram of earlier string
Explanation:
I will explain the program with an example:
Suppose array = ['code', 'doce', 'ecod', 'framer', 'frame']
Now the for loop works as follows:
At first iteration:
first string of array is 'code'
if ''.join(sorted(string)) not in s: this is an if statement which has two method i.e. join() and sorted(). First each letter of the string i.e. 'code' is sorted in alphabetical order then these separated characters are joined together into a word with join() method. So
sorted(string) becomes:
['c', 'd', 'e', 'o']
and ''.join(sorted(string)) becomes:
cdeo
Now if ''.join(sorted(string)) not in s condition checks if cdeo is not in s set. This is true so the statement:
output.append(string) executes which appends the string to output list. So now output has:
['code']
Next s.add(''.join(sorted(string))) statement adds the sorted and joined string of array to s set. So the set has:
{'cdeo'}
So at each iteration each word from the array is sorted and joined and then checked if output array contains that word or not. If not then it is added to the output array otherwise not. For example at 2nd iteration the word 'doce' which is anagram of code and it is checked when it is sorted and joined and it becomes cdeo which is already in output array. So this is how the anagram is removed from the array. At the end the output array which returns the remaining array in sorted order is returned by this method. The screenshot of the program along with its output is attached.