Question on for loop

Rick Johnson rantingrickjohnson at gmail.com
Mon Mar 4 10:41:33 EST 2013


On Monday, March 4, 2013 6:18:20 AM UTC-6, newtopython wrote:

[Note: Post has be logically re-arranged for your comprehensive pleasures]

> for character in secretWord:
>         if character not in lettersGuessed:
>         return True
> return False
> 
> What this code is doing is only checking the first
> character of secretWord and then returning True or False.
> How do I get it to iterate through ALL of the characters
> of secretWord?

Your code is a fine example of:  "attempting to solve too many problems at the same time". If you are having trouble understanding how to iterate over a sequence, then why would you complicate that learning experience by injecting other unsolved problems into the mix? First, solve the iteration problem. Then expand.

 ## START INTERACTIVE SESSION ##
 py> s = 'multiplicity'
 py> for char in s:
 ...     print char	
 m
 u
 l
 t
 i
 p
 l
 i
 c
 i
 t
 y
 ## END INTERACTIVE SESSION ##

Now, we have a simple base from which to build! 

> In the piece of code [ABOVE], secretWord is a string and
> lettersGuessed is a list. I'm trying to find out if ALL
> the characters of secretWord are included in
> lettersGuessed, even if there are additional values in the
> lettersGuessed list that aren't in secretWord.

First, step away from your interpreter! Now, grab a pen and paper and write down the steps required to compare two sequences in real life.

1. Create a list of "letters guessed" and a string representing the "secret word".

secretWord = 'multiplicity'
lettersGuessed = 'aeiouy'

2. For each letter in "secretWord", look in "lettersGuessed" and see if you can find the letter, then make a note of your findings. If the letter is in IN both sequences, write "[letter]=True", if not, write "[letter]=False".

However, this algorithm is rather naive. What happens if one or both list contain the same letter numerous times (f.e. "multiplicity" has 3 "i" chars)? Do we want the user to provide a guess for all three "i" chars, or will just a single guess al la "price is right" will do the trick? 

Also, do we care about the "char order"? Or are we merely allowing the user to guess all the letters of the word in ANY order (that seems to be your intent here!)?

In any event i am not going to just "gift wrap" and answer for you. There are many methods of solving this problem, some are elegant, some or not elegant, some use built-in functions, some use list comprehensions, and some could just use a for loop and a single built-in function. I would highly suggest that you figure this out using the latter. Until you can achieve this, forget about list comprehension or any advanced stuff. 

But most importantly: Build your code in small incremental steps and solve ONE issue at a time. This is the path of a wise problem solver.



More information about the Python-list mailing list