Problems with string and lists (searching and replaceing)

Ulrich Petri ulope at gmx.de
Sun Sep 21 20:40:30 CEST 2003


"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-----


HTH

Ciao Ulrich






More information about the Python-list mailing list