[Tutor] Word Jumble - Chpt4 (Explanation)
Prasad, Ramit
ramit.prasad at jpmorgan.com
Thu May 16 22:22:22 CEST 2013
Arvind Virk wrote:
> Hi guys!
>
> This is my first post so go gentle. I'm just getting into Python programming and am having an issue
> understanding the Word Jumble Game.
>
> import random
>
> WORDS = ('python','jumble','easy','difficult','lower','high')
> word = random.choice(WORDS)
> correct = word
> jumble = ""
>
> while word:
> position = random.randrange(len(word))
> jumble += word[position]
> word = word[:position] + word[(position+1):]
>
> ======
>
> I cannot understand what it is trying to do in the while loop.
> If the word was python and position lets say was 3 then jumble would = python(3). I cannot understand
> what the next line does! Please help!
>
> Thanks in advance!
>
The best way to understand a program is to watch what it is
doing and follow through the code. This is called debugging.
Simple programs like this you might be able to debug in your
mind but in a real program chances are you will need a debugger
or some other method. A very common way to debug is to put in
print statements so you can follow the actions of data. Look
at the code I put below and the output. Can you follow?
>>> word = 'python'
>>> jumble = ""
>>> while word:
... position = random.randrange(len(word))
... print 'position {0} | jumble "{1}"'.format( position, jumble )
... tempchar = word[position]
... jumble += tempchar
... word = word[:position] + word[(position+1):]
... print 'After jumble "{0}" | word "{1}" | tempchar {2}'.format( jumble, word, tempchar )
...
position 5 | jumble ""
After jumble "n" | word "pytho" | tempchar n
position 2 | jumble "n"
After jumble "nt" | word "pyho" | tempchar t
position 3 | jumble "nt"
After jumble "nto" | word "pyh" | tempchar o
position 1 | jumble "nto"
After jumble "ntoy" | word "ph" | tempchar y
position 0 | jumble "ntoy"
After jumble "ntoyp" | word "h" | tempchar p
position 0 | jumble "ntoyp"
After jumble "ntoyph" | word "" | tempchar h
So based on the above output I would say that it is removing a
random character from word and adding it to jumble to create a
jumbled version of the word. Of course, the std library
can do it for you better. :) I leave the exercise of actually
understanding the character manipulation to you as a learning
exercise, but if you get stuck feel free to post back.
>>> t = list("python")
>>> random.shuffle(t)
>>> ''.join(t)
'optynh'
~Ramit
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.
More information about the Tutor
mailing list