[Tutor] Re: Please critique my hangman.py program (original) (raw)
Alan Gauld alan.gauld at blueyonder.co.uk
Sun Jul 25 10:33:32 CEST 2004
- Previous message: [Tutor] Re: Please critique my hangman.py program
- Next message: [Tutor] Permutations?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
>> # Evaluate guess against word >> lettercorrect = 0 >> for i in range(wordlength): >> if guess == word[i]: >> correctsofar[i] = guess >> lettercorrect=1 >> lettersguessed = lettersguessed + 1 > >Personally I'd use a while loop here: > > i,lettercorrect = 0,False > while i < wordlength and not lettercorrect:_ _> if guess == word[i]: > correctsofar[i] = guess > lettercorrect=True > lettersguessed += 1 > i += 1 > >Same length but I just think the test expresses the intention of >the loop better.
I think that there may be a problem with this. For a word that has 2 of the same letter. The original way checks for that, while the latter way would make "lettercorrect" = to "True" by the first pass and the while loop would terminate.
Good catch! Although it actually highlights a bug in the first version too in that a single letter occurruing twice will show up twice in the letters_guessed total. But I guess(sic) that thats less of an issue than not filling in all of the blanks... :-)
It can be fixed by pulling it out of the loop and using an if statement:
# Evaluate guess against word
letter_correct = False
for i in range(word_length):
if guess == word[i]:
correct_so_far[i] = guess
letter_correct=True
if letter_ correct:
letters_guessed = letters_guessed + 1And my mistake can also be fixed by simply eliminating the second clause of the while test, but then its not much advantage over the for/range combo...
Alan G.
- Previous message: [Tutor] Re: Please critique my hangman.py program
- Next message: [Tutor] Permutations?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]