开发者

Python Logic Help:

I am writing a game where there are two losing conditions:

  1. Forming a word longer than 3 letters. Bee is okay, Beer is not.
  2. Forming a word that can't be made into a longer word. Zebra is okay, Zebras is not.

Wordlist is a list of words, frag is the previous fragment and a is the new letter a player enters. so frag may look like 'app' and a maybe 'l' with the idea of forming the word apple.

def getLoser(frag, a, wordlist):
word = frag + a

if len(word) > 3:

    if word in wordlist:
        print 'word in wordlist'
        return True
    
    else:
        for words in wordlist:
            if words[:len(word)] == word:
                print words,':', word
                print 'valid word left'
                return False
            
            else: 
                print words[:len(word)]
                print开发者_运维百科 words,':', word
                print 'false found'
                return True
else:
    return False

For some reason when I enter my 4th letter, it automatically goes to the else in the for loop, even when the if statement functions in the for loop works correctly when I test it alone on dummy data in the interactive trail.

Here is output for the frag alg and the letter e with the word algebra in the wordlist.

e

aa

aa : alge

false found

True

Any ideas?


You are overcomplicating things. If the new fragment is less than 3 letters, it is automatically OK. If not, it must be the start of some word and not be a word itself to be OK.

>>> words = { "apple" }
>>> def isOK( fragment, letter ):
...     word = fragment + letter
...     if len( word ) <= 3: return True
...     return word not in words and any( w.startswith( word ) for w in words )
...
>>> isOK( "a", "p" )
True
>>> isOK( "ap", "p" )
True
>>> isOK( "app", "l" )
True
>>> isOK( "appl", "l" )
False
>>> isOK( "appl", "e" )
False

(It would be possible to combine the two tests above into one conditional statement:

return len( word ) <= 3 or word not in words and any( w.startswith( word ) for w in words )

but I think that is overly obscure.)

I can't follow the logic of your code above; it is rather confusingly written. (Why is words a string, for instance?) Try writing the logic of the game in pseudocode before trying to implement it -- that may help you sort out your thoughts.


Here's a clearer version:

def isOK( word ):
    condition_one = len( word ) > 3 and word in words
    condition_two = not any( w.startswith( word ) for word in words )

    return not( condition_one or condition_two )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜