Problems with string and lists (searching and replaceing)

Colin Fox cfox at cfconsulting.ca
Sun Sep 21 23:08:04 CEST 2003


On Sun, 21 Sep 2003 20:40:30 +0200, Ulrich Petri wrote:

> "jblazi" <jblazi at hotmail.com> schrieb im Newsbeitrag
> news:pan.2003.09.21.06.55.07.16000 at hotmail.com...
>> I shall have a computer science class this year and I decided to use
>> Python. It is my favourite language and I have used it for many years. Now
>> I thought, one of our first "real" programs, in our pre-graphical and
>> pre-class state, would be to write simple program that works like this:
>>
>> One of the pupils enters a word. It should be a valid German word
>> consisting of five letters, for example 'abcde' (which is not a German
>> word by the way).
>>
>> The the other player may enter a guess which must be a five letter word as
>> well, for example 'xbxxx'. Then the system answers with the string '-*---'
>> as the 'b' in 'xbxxx' was correct and at the right place as well.
>>
>> Had the second player entered 'xxxbx', the system had responded with
>> '---.-', as the 'b' is correct but not correctly positioned.
>>
>> The second player must find out the original word.
>>
> 
> Hm sth. like this?
> 
> -----code------
> def mastermind(word, guess):
>     if len(word) != len(guess):
>         return "Error"
>     ret = ["-"]*len(word)
>     counter = 0
>     for lw, lg in zip(word, guess):
>         if lw == lg:
>             ret[counter] = "x"
>         else:
>             if lg in word:
>                 ret[counter] = "."
>         counter += 1
>     return "".join(ret)
> 
>>>> mastermind('haus', 'hasu')
> 'xx..'
>>>> mastermind("jaguar", "januar")
> 'xx-xxx'
> -----code-----

Here's an alternative. I took out the 'if lg in word' logic,
since that doesn't take into account duplicates and therefore
would be misleading (ie 'jaguar','jaaaaa' would return 'x.....',
but there aren't 5 a's in the word).

#!/usr/bin/env python
import string
                                                                                
def wordcheck(word, guess):
    outstr = []
    if len(word) != len(guess):
        raise "Wrong number of letters in guess."
                                                                                
    for x in range(len(word)):
        outstr.append( ['-','*'][(word[x]==guess[x])] )
                                                                                
    return string.join(outstr,'')
                                                                                
res = wordcheck('Colin','Coolo')
print res
                                                                                





More information about the Python-list mailing list