RezaCode73 RezaCode73 - 1 month ago 19
Python Question

Test_anagram function

I'm wanting to define a function called test_anagram that takes no arguments.
It should call a previous function 'anagram' and test if it's working correctly.
The function needs to print out whether it's passed or not with true/false underneath each pair of words. (so far I have it to show one of the anagrams as false to test.

My code:

# -*- coding: utf-8 -*-


def anagram(str1,str2):
# string to list
str1 = list(str1.lower())
str2 = list(str2.lower())

#sort list
str1.sort()
str2.sort()

#join list back to string
str1 = ''.join(str1)
str2 = ''.join(str2)

return str1 == str2

print(anagram('trainer', 'terrain')) #true
print(anagram('trainer', 'shoe')) #false


(this bottom half is what I'm having the problem with).

def test_anagram():
strings = [("plane","panel"),("traps","parts"),("state","man"), ("nails","snail"),("reset","trees"),("later","alert")] strings
for str1,str2 in strings:
print(str1,str2) # print each string
anagram(str1,str2)


test_anagram()
print(anagram('plane', 'panel'))

print(anagram('traps', 'parts'))

print(anagram('state', 'man'))

print(anagram('nails', 'snail'))

print(anagram('later', 'alert'))


At the moment it prints to the terminal like this:

plane panel
traps parts
state man
nails snails
reset trees
later alert
True
True
False
True
True


Where as I'm wanting it to print like this:

plane panel
True
traps parts
True
state man
False
nails snails
True
reset trees
True
later alert
True


I'm not sure how to do this so any help would be greatly appreciated,
Thank you.

Answer

Instead of

   for str1,str2 in strings: 
   print(str1,str2) # print each string
   anagram(str1,str2)

use

   for str1,str2 in strings:                       # OK - no change
       print(str1,str2) # print each string        # added indentation
       print(anagram(str1,str2))                   # added indentation + print()

(and delete all now already redundant lines after the line test_anagram().)