Doug Reid wrote:
Now here is the code I'm having trouble following:
while word:
    position = random.randrange(len(word))
    jumble += word[position]
    word = word[:position] + word[(position + 1):]
position = random.randrange(len(word)). This will create a starting point for the program to pick a letter out of a word at random using the length of the word as a range I think. Like if the word is 'python' and since it has 6 letters, random.randrange(len(word)) will pick a random starting point such as the letter 'y' for example. It's gonna be inside a while loop, so the next time it runs, 'python' will be 'pthon' and the random range will be 5 letters and on down till there is no more letters, is this right?

`position` is an integer. It is the index of the letter we want to put into `jumble`. The first line generates a random index, the second line copies the letter and append it to `jumble`, and the third line removes that letter from `word`.

Ok, so everyone of the letters that was 'extracted' from the word 'python' will be put into the variable 'jumble' that was defined as empty. This is the part that troubles me: word = word[:position] + word[(position + 1):]

How do we remove a single letter? In python, string is immutable; we must create a new string that has the required property (i.e. letter in `position` removed).

Rather than removing, we copied the part of string before `position` (word[:position]) and after `position` (word[position+1:]) and concatenating them together to become our new `word`.

How does the slicing works?

The standard model for "slicing and indexing" in python is like this:

-6  -5  -4  -3  -2  -1
 +---+---+---+---+---+---+
 | p | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6

Let's say `position` is 3 (i.e. the letter "h").

word[:3] is:

-6  -5  -4  -3  -2  -1
 +---+---+---+---+---+---+
 | p | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
 |___________|
   word[0:3]

which is "pyt"

while

word[3+1:] -> word[4:] is:

 -6  -5  -4  -3  -2  -1
 +---+---+---+---+---+---+
 | p | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
                 |_______|
                 word[4:6]

which is "on"

concatenating "pyt" + "on", we get "pyton" (i.e. "h" removed)


An extended version of the line that may be more easily digestible:

letters_before_position = word[:position]
letters_after_position = word[position+1:]
word = letters_before_position + letters_after_position


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to