开发者

Python- Replace all occurrences of letter at specific position on a string

Trying to create the TV game-show "Lingo" in Python.

In the game, players are trying to guess a five letter word. They start off my randomly guessing a five letter word. The game board then will light up showing how the word they guessed matches up with the actual word.

For example, if the real word is "gorge" and the players guess "eagle"-- the board will show that 'e' and 'g' are in the real word, but that they are not in the correct position with respect to the real word "gorge." (The g's are in the [0] and [3] index, while in eagle they're in the [2] index).

If the word was "happy" and the users guessed "harpy", the board would display that three of the letters were in the real word AND they were correctly positioned. (h-a-y).

In the Python implementation I am highlighting that a letter is correct, but in the wrong posit开发者_开发百科ion with a '~' under it. If it is correct and in the correct position, I put a '!' under it.

The important function looks like this:

  wordGuess = input("Guess a letter: ")[0:5]
    for letter in wordGuess:
        if letter in realWord:
            if wordGuess.find(letter) == realWord.find(letter)

// Don't know what to do from here

If there are more than one occurrence of a correct letter, with one of the letters incorrectly matching the position of the letter in the realWord-- how do I detect it?

For example, if the real word was "lasts" and someone were to guess "brass", the first 's' in brass is a correct letter, but in the incorrect position, while the second 's' is a correct letter and a correct position.

So what's the best way to implement a function that can check to see if a letter if correct and in the correct position (and denote it with a !) or denote that it is a correct letter in the wrong position with a ~


To find common letters regardless of position:

In [1]: set('harpy') & set('happy')
Out[1]: set(['a', 'h', 'p', 'y'])

To get a boolean flag indicating whether each letter of 'harpy' is present in 'happy' at any position:

In [17]: [l in 'happy' for l in 'harpy']
Out[17]: [True, True, False, True, True]

In the above code, 'happy' can be replaced with the set intersection from the first snippet.

Lastly, to get a boolean flag for each position indicating whether the letter is in the correct position:

In [2]: [l==r for l,r in zip('happy','harpy')]
Out[2]: [True, True, False, True, True]

To combine the above into a complete solution:

In [49]: real='lasts'

In [50]: guess='brass'

In [51]: exact=[l==r for l,r in zip(real,guess)]

In [52]: approx=[l in real for l in guess]

In [53]: chars=[[' ','~'],['!','!']]

In [54]: print guess, '\n', ''.join(chars[e][a] for e,a in zip(exact,approx))
brass 
  ~~!

(In case you're wondering about using booleans to index into an array, they're implicitly converted to integers: False=0 and True=1.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜