Python the Hard Way ex48 -


i'm having trouble getting code below test correctly. test_errors() function isn't working correctly, feel i've set code right. line 25 thought work, i'm not having luck.

line25:

elif not in direction or verb or stop or noun:    scan_result = scan_result + [('error', i)] 

whole code:

direction = ('north', 'south', 'east', 'west', 'up', 'down', 'left', 'right', 'back') verb = ('go', 'stop', 'kill', 'eat') stop = ('the', 'in', 'of', 'from', 'at', 'it') noun = ('door', 'bear', 'princess', 'cabinet') lexicon = {direction: 'direction',        verb: 'verb',        stop: 'stop',        noun: 'noun',        }   def scan(user_input):     words = user_input.split()     scan_result = []     try:         in words:             if i.isdigit():                 scan_result = scan_result + [('number', int(i))]             elif i.lower() in direction or verb or stop or noun:                 j in lexicon:                     k in j:                         if i.lower() == k:                             scan_result = scan_result + [(lexicon[j], i)]             elif not in direction or verb or stop or noun:                 scan_result = scan_result + [('error', i)]         return scan_result     except valueerror:         return none 

test_error function:

def test_errors():     assert_equal(lexicon.scan("asdfadfasdf"), [('error', 'asdfadfasdf')])     result = lexicon.scan("bear ias princess")     assert_equal(result, [('noun', 'bear')                           ('error', 'ias'),                           ('noun', 'princess')]) 

the mistake in code not line 25 line 20. checking variable return true unless variable none or falsey. when if verb, if verb set tuple, evaluate true. since first elif evaluates true, block gets executed , code continues on outside if..elif..else without evaluating second elif i.e. 3rd condition, suffers same problem first elif. python tries find true condition , finds one, stops checking other conditions.

you want check if word either in direction or verb or stop or noun. sadly, either..or pattern doesn't exist in python.

the correct , pythonic way check following:

elif i.lower() in direction + verb + stop + noun: ... elif not in direction + verb + stop + noun: ...

also test_errors function incorrect. lexicon dict while scan function , 2 separate, can't call lexicon.scan(). should scan().

assert_equal(scan("asdfadfasdf"), [('error', 'asdfadfasdf')])


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -