Issue
How would I do: "if this function prints "Anagram" then print something else". I also would somehow just like to see if it would print that but not have it print it.
These are the files, I'm working on findAnagrams and comparewords cannot be changed.
comparewords.py
def word_compare(x, y='steal'):
if isinstance(x, str) and isinstance(y, str) == True:
sorted_x = sorted(x)
sorted_y = sorted(y)
if sorted_x == sorted_y:
print('Anagram')
else:
mytuple = (x, y)
print(mytuple)
else:
print("Those aren't strings!")
findtheanagram.py
from WordCompare import word_compare
def findanagram(words):
for i in words:
for j in words:
if word_compare(i,j) == "Anagrams":
print(word[i]+ ":" + j)
words = ['tar', 'rat', 'face', 'cafe', 'hello']
findanagram(words)
How do I do "if the function prints x then do x and not have it print anything"?
Solution
one way of solving your problem, using dictionary to save the sorted word and save the same sorted word in a list , make the element in list anagrams
def findanagram(words):
dic = {}
for word in words:
if not isinstance(word, str):
continue
sorted_word = ''.join(sorted(word))
if sorted_word not in dic:
dic[sorted_word] = []
dic[sorted_word].append(word)
return [anagrams for anagrams in dic.values() if len(anagrams)>1]
words = [1,'tar', 'rat', 'face', 'cafe', 'hello']
result = findanagram(words)
print(result)
output
[['tar', 'rat'], ['face', 'cafe']]
improvement in your code
instead of using print, your function need to return True and False, stating that the given two words are anagram or not respectively.
so your code in compareword.py should be like
def word_compare(word1, word2):
if not isinstance(word1, str) or not isinstance(word2, str):
return False # you can use log here to give reason
sorted_word1 = ''.join(sorted(word1))
sorted_word2 = ''.join(sorted(word2))
if sorted_word1==sorted_word2:
return True
else:
return False
# you can just use
# return sorted_word1 == sorted_word2
and in file findtheanagram.py
you can do
def findtheanagram(words):
result = []
for i, v in enumerate(words):
for j in range(i+1, len(words)): # considering minimum 2 elements
word1 = v
word2 = words[j]
if word_compare(word1, word2):
result.append((word1, word2))
return result
Answered By - sahasrara62
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.