I am a somewhat experienced Java programmer who is re-implemting some code in Python, as I am just learning the language. The issue that I am having is that a method is returning nothing when I pass in global variables, but returning intended code when a literals are passed in. The code returns a list of words of the specified length passed in, starting with the string passed in. For example:
print getNGramBeginsWords("ha", 5)
returns
['HAAFS', 'HAARS', 'HABIT', 'HABUS', 'HACEK', 'HACKS', 'HADAL', 'HADED', 'HADES',
'HADJI', 'HADST', 'HAEMS', 'HAETS', 'HAFIZ', 'HAFTS', 'HAHAS', 'HAIKA', 'HAIKS',
'HAIKU', 'HAILS', 'HAINT', 'HAIRS', 'HAIRY', 'HAJES', 'HAJIS', 'HAJJI', 'HAKES',
'HAKIM', 'HAKUS', 'HALAL', 'HALED', 'HALER', 'HALES', 'HALID', 'HALLO', 'HALLS',
'HALMA','HALMS', 'HALON', 'HALOS', 'HALTS', 'HALVA', 'HALVE', 'HAMAL', 'HAMES',
'HAMMY', 'HAMZA', 'HANCE', 'HANDS', 'HANDY', 'HANGS', 'HANKS', 'HANKY', 'HANSA',
'HANSE', 'HANTS', 'HAOLE', 'HAPAX', 'HAPLY', 'HAPPY', 'HARDS', 'HARDY', 'HARED',
'HAREM', 'HARES', 'HARKS', 'HARLS', 'HARMS', 'HARPS', 'HARPY', 'HARRY', 'HARSH',
'HARTS', 'HASPS', 'HASTE', 'HASTY', 'HATCH', 'HATED', 'HATER', 'HATES', 'HAUGH',
'HAULM', 'HAULS', 'HAUNT', 'HAUTE', 'HAVEN', 'HAVER', 'HAVES', 'HAVOC', 'HAWED',
'HAWKS', 'HAWSE', 'HAYED', 'HAYER', 'HAYEY', 'HAZAN', 'HAZED', 'HAZEL', 'HAZER',
'HAZES']
as it should. However,
print inputString
print numLetters
print getNGramBeginsWords(inputString, numLetters)
returns
ha
5
[]
inputString and numLetters are global variables, which I have seen called "dangerous," though I don't know why, and was thinking that they could be the cause of this oddity? Even local copies of the global variables being used as parameters doesn't help. Perhaps I need to use the "global" keyword in the parameters of the method, although from my research it appears you don't need the "global" keyword unless you are changing the global variable? Any suggestion or help would be appreciated. On the off chance that it is an issue with the method, here it is:
def getNGramBeginsWords(nGram, length):
dict = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
nGram = nGram.upper()
words = []
for line in dict:
if(len(line)>0):
if(len(nGram)>len(line.strip()) | len(line.strip())!= length):
continue
s = line.strip()[:len(nGram)]
if(s == nGram and len(line.strip()) == length):
words.append(line.strip())
return words
print type(numLetters)before callinggetNGramBeginsWords, do you get<type 'int'>or<type 'str'>? I suspect you get the latter, so that for each line, you compare the length of the line to the string"5". (Side note:dictis the name of a type in Python. You can re-use these as local variables, it just makes for a surprise when you then try to make a dict by invokingdict. Maybe usestreamfor the variable name instead :-) )|you want inif(len(nGram)>len(line.strip()) | len(line.strip())!= length). Because, in Python|is Bitwise OR andoris Boolean OR.dictfile. Try usingwith open(..., 'r') as dict:statement.