There seemed to be a good amount of confusion in using accumulators to print out the reverse of a string. This combines a few advanced ideas so let us try to break it down into its pieces. First, when we accumulate a string, we are trying to "build up" the string piece by piece. In this case, we are trying to add one letter at a time from a string. The solution we had in class was:
reverse = "" for i in range(len(word)-1, -1, -1): reverse += word[i] print(reverse)Let's step through this one iteration at a time. If we were to code this up without the loop, we can see what is happening at each iteration
#These are the initial steps >>> word = "example" >>> reverse = "" >>> i = len(word)-1 >>> i 6So our loop starts with i having the value len(word)-1, which is what we defined in our range function. Now we'll start accumulating:
>>> reverse += word[i] #add the last letter in the word as the first letter # of reverse >>> reverse 'e' >>> i = i-1 #one iteration is done, move on to the next value >>> i 5 >>> reverse += word[i] >>> reverse 'el' >>> i = i-1 >>> i 4 >>> reverse += word[i] >>> reverse 'elp' >>> i = i-1 >>> i 3 >>> reverse += word[i] >>> reverse 'elpm' >>> i = i-1 >>> i 2 >>> reverse += word[i] >>> reverse 'elpma' >>> i = i-1 >>> i 1 >>> reverse += word[i] >>> reverse 'elpmax' >>> i = i-1 >>> i 0 >>> reverse += word[i] >>> i = i-1 >>> i -1Another solution to the problem constructs the loop in a more traditional way, but indexes differently:
reverse= "" for i in range(1, len(word)+1): reverse += word[len(word)-1]The loop looks different, but the accumulation is the same:
>>> word = "example" >>> reverse = "" >>> i = 1 >>> reverse += word[len(word)-i] >>> reverse 'e' >>> i=i+1 >>> reverse += word[len(word)-i] >>> reverse 'el' >>> i=i+1 >>> i 3 >>> reverse += word[len(word)-i] >>> reverse 'elp' >>> i=i+1 >>> i 4 >>> reverse += word[len(word)-i] >>> reverse 'elpm' >>> i=i+1 >>> i 5 >>> reverse += word[len(word)-i] >>> reverse 'elpma' >>> i=i+1 >>> i 6 >>> reverse += word[len(word)-i] >>> reverse 'elpmax' >>> i=i+1 >>> i 7 >>> reverse += word[len(word)-i] >>> reverse 'elpmaxe' >>> i=i+1 >>> i 8 >>>