This is my first post.
I have a block of code that I am trying to run nosetests on.
There is a very simple fix to make this code run and that is by putting the integers in quotes.
What I want to accomplish is to have a dictionary that uses strings and integers in the dictionary. Here is my dictionary with a scan function.
lexicon = {
'1234': 'number',
3: 'number',
91234: 'number'
}
def scan(sentence):
results = []
words = sentence.split()
for word in words:
word_type = lexicon.get(word)
results.append((word_type, word))
return results
The above code is imported into my test file which contains this block of code.
from nose.tools import *
from ex48 import lexicon
def test_numbers():
assert_equal(lexicon.scan('1234'), [('number', '1234')])
result = lexicon.scan('3 91234')
assert_equal(result, [('number', 3),
('number', 91234)])
The '1234' part runs just fine.
But, is there a location in the code where I can use int() so that when split() is ran on "3 91234" it will return two integers and use my lexicon dictionary correctly to call back the appropriate values?
Thank you for your help!
You can use isnumeric() method to check if the string is numeric and than do a conversion to int.
lexicon = {
'1234': 'number',
3: 'number',
91234: 'number'
}
def scan(sentence):
results = []
words = sentence.split()
for word in words:
if word.isnumeric(): #change
word = int(word) #change
word_type = lexicon.get(word)
results.append((word_type, word))
return results
Please note that after this change you need to store all the numeric keys as int else it will not fetch number keys stored as string.