0

私は言語を学んでいるので、Python でいくつかのコードを再実装している経験豊富な Java プログラマーです。私が抱えている問題は、グローバル変数を渡すとメソッドが何も返さないが、リテラルが渡されると意図したコードを返すことです。コードは、渡された文字列で始まる、渡された指定された長さの単語のリストを返します。に例を示します。

print getNGramBeginsWords("ha", 5)

戻り値

['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']

あるべきように。でも、

print inputString
print numLetters
print getNGramBeginsWords(inputString, numLetters)

戻り値

ha
5
[]

inputString と numLetters はグローバル変数で、「危険」と呼ばれているのを見たことがありますが、理由はわかりませんが、これらがこの奇妙な原因である可能性があると考えていましたか? パラメータとして使用されているグローバル変数のローカル コピーでさえ役に立ちません。メソッドのパラメーターで「global」キーワードを使用する必要があるかもしれませんが、私の調査によると、グローバル変数を変更しない限り「global」キーワードは必要ないようです。任意の提案や助けをいただければ幸いです。それがメソッドの問題である可能性が低い場合は、次のとおりです。

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
4

1 に答える 1

1

tl;dr: グローバル変数はこれとは関係ありません。長さパラメーターとして int ではなく文字列を渡していることはほぼ確実です。あなたのコードには多くの冗長性がありました。

あなたのコードには、文体と実質の両方で、多くの明らかな問題があります。

def getNGramBeginsWords(nGram, length):
    # dict is the name of a builtin function, which you are confusingly overwriting
    # dict = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    wlist = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    nGram = nGram.upper()
    words = []
    for line in wlist:
        # an empty string evaluates to False in a binary context; also no need for those brackets
        stripline = line.strip().upper() # you keep doing this; I added the upper here.
        # you don't need this if, because you immediately test length
        #if stripline: #I know I changed this, but you only refer to the stripped version below 
        # pipe | is bitwise OR. I bet you don't want that
        if len(nGram)>len(stripline) or len(stripline)!= length:
            continue
        # s = stripline[:len(nGram)] #you only use this once
        # you don't need to check that stripline is of length again; you already did that
        # also, you can just use `endswith` instead of slicing
        if stripline.endswith(nGram):
            words.append(stripline)
    return words

そして、コメントなし:

def getNGramBeginsWords(nGram, length):
    wlist = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    nGram = nGram.upper()
    words = []
    for line in wlist:
        stripline = line.strip() # you keep doing this
        # you can merge these two ifs
        if len(nGram)>len(stripline) or len(stripline)!= length:
            continue
        if stripline.endswith(nGram):
            words.append(stripline)
    return words

隣接する 2 つの if をマージします。

def getNGramBeginsWords(nGram, length):
    wlist = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    nGram = nGram.upper()
    words = []
    for line in wlist:
        stripline = line.strip().upper() # you keep doing this
        # you can merge these two ifs
        # also this renders the comparison of ngram and stripline lengths redundant
        if (len(stripline) == length) and stripline.endswith(nGram):
            words.append(stripline)
    return words

では、この最後のバージョンを見てみましょう。おかしなことに、 に対して実際に数値演算を実行することはありませんlength。長さは数値であると想定されているため、強制的に数値にしたい場合があります。変換できない場合は、例外が発生します。

def getNGramBeginsWords(nGram, length):
    wlist = open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r')
    nGram = nGram.upper()
    words = []
    length = int(length) # force to an int
    assert isinstance(n, int) # or do this if you prefer to get an exception on all invalid input
    for line in wlist:
        stripline = line.strip().upper() # you keep doing this
        # you can merge these two ifs
        if (len(stripline) == length) and stripline.endswith(nGram):
            words.append(stripline)
    return words

最後に、実際にファイルを明示的に閉じることはありません。しばらくぶらぶらします。withコンストラクトを使用して自動的に閉じることをお勧めします。

def getNGramBeginsWords(nGram, length):
    with open('/home/will/workspace/Genie/src/resources/TWL06.txt', 'r') as wlist:
        nGram = nGram.upper()
        words = []
        length = int(length) # force to an int
        assert isinstance(n, int) # or do this if you prefer to get an exception on all invalid input
        for line in wlist:
            stripline = line.strip().upper() # you keep doing this
            #you should be using `endswith` instead of the slice
            if (len(stripline) == length) and stripline.endswith(nGram):
                words.append(stripline)
        return words
于 2013-07-17T20:54:43.060 に答える