7 reverse


#1

Alright below is my code for this exersise. It works, yet i dont entirely understand why it works.
If i remove the line
reversed_text.append(text[-1:]) before the loop, and change variables letter and letter_2 to -1 and -2 respectively (in order to slice and the caracters one by one from the string and append them in the reverese order) nothing happens - the code only slices the last letter of a string. Yet when i slice out and append last symbol of the string, and go looping for the reamining - it works. Please explain this to me, it seems that i grabbed this intuitively yet i lack rational understanding.


text = raw_input()
def reverse(text):
    reversed_text = []
    letter = -1
    letter_2 = 0
    reversed_text.append(text[-1:])
    for n in range(len(text)):
        reversed_text.append(text[letter:letter_2])
        letter -= 1
        letter_2 -= 1
    
        
    return ''.join(reversed_text)

print reverse(text)


#2

@frol110,

def reverse(text):
    reversed_text = []
    letter = -1
    letter_2 = 0
    reversed_text.append(text[-1:])
    print(reversed_text)
    for n in range(0,len(text)):
        print("n={3}\ttext[{0}:{1}] {2}".format(
            letter,letter_2,text[letter:letter_2],n))
        reversed_text.append(text[letter:letter_2])
        letter -= 1
        letter_2 -= 1
    
        
    return ''.join(reversed_text)
text="Text to reverse"
print reverse(text)


print("===================================")
def reverse(text):
    reversed_text = []
    letter = -1
    letter_2 = 0
    #reversed_text.append(text[-1:])
    print(reversed_text)
    for n in range(len(text)):
        #print letter-n*1
        #print text[letter-n*1]
        print("n={2}\ttext[{0}] {1}".format(
            letter-n*1,text[letter-n*1],n))
        #reversed_text.append(text[letter-n*1])
        #letter -= 1
        #letter_2 -= 1
    
        
    return ''.join(reversed_text)
text="Text to reverse"
print reverse(text)

Shorthand

text="Text to reverse"
print text[len(text)+1::-1]

From https://docs.python.org/3/library/stdtypes.html

x in s True if an item of s is equal to x, else False (1) 
x not in s False if an item of s is equal to x, else True (1) 
s + t the concatenation of s and t (6)(7) 
s * n or n * s equivalent to adding s to itself n times (2)(7) 
s[i] ith item of s, origin 0 (3) 
s[i:j] slice of s from i to j (3)(4) 
s[i:j:k] slice of s from i to j with step k (3)(5) 
len(s) length of s   
min(s) smallest item of s   
max(s) largest item of s   
s.index(x[, i[, j]]) index of the first occurrence of x in s 
          (at or after index i and before index j) (8) 
s.count(x) total number of occurrences of x in s   


#3

I just save 15% of coding space by shopping with Geico insurance. Just kidding, I don't know why you need 2 counters to reverse the text, I just did it with this:

def reverse(text):
    result = []
   
    for i in range(len(text)):
        result.append(text[len(text)-i-1])
    return ''.join(result)

I learned the "".join(result) from you so I want to pay it back by offer this simpler solution so you can easily follow what the code is doing.

Best,


#5

Can you explain this line to me: result.append(text[len(text)-i-1])

I'm probably being dim but to me that looks like it should just displace the letter order by one instead of reversing it.


#6

So imagine your text is C.A.T

len(text)=3 but the way C.A.T is indexed is C = 0, A = 1, T = 2

So when I reverse print, I print text[len] which is 3, but the position I want is 2 (for the T above), so I have to subtract 1. Then the i counter will go up each time in the for loop, which bring me back to position 0, the first letter of the text.

The -1 is due to the way the machine count, starting from 0 and the way we count, starting from 1. Len(text) counts the way we count, and append() counts the way machine counts, hence the -1 to offset it.

Hope it helps.


#7

Sorry, that's just confused me. Could you try explaining more simply?


#8

Ok...let try this again:

Humans count:

1 2 3
C A T

so text(len) = 3

Computers Count:

0 1 2
C A T

for i (my counter) starting at 0 and going to text.len()-1, which is 2, because I am talking to computer, so I have to count like it counts.

text.len() which is 3 - counter - 1 = 2     (counter = 0 on the first pass through the for loop)
           so the computer is going to print   the "2" position, which is the letter "T"

the second time around, my counter = 1

text.len() which is 3 - counter - 1 = 1 (counter = 1 on the second pass through the for loop)
so the computer is going to print the "1" position, which is the letter "A"

the third time around, my counter = 2

text.len which is 3- counter - 1 = 0 (counter = 1 on the second pass through the for loop)
so the computer is going to print the "0" position, which is the letter "C"

Again, hope this helps.


#9

Great method,

However you can replace:

result.append(text[len(text)-i-1])

with:

result.append(text[-1-i])

This is because the index -1 will take the last index in a list. If you then use - i to iterate through each index of the list in reverse order.


#10

Thank you for the tip. I was coming at it from a C++ background and of course Python would have a simpler way to handle array.

So here is the simplest working code for those who are interest:

def reverse(text):
    result = []
   
    for i in range(len(text)):
        result.append(text[-1-i])          
        #text[-1] will return the last index on the list: the last character in the text and attach it to the result as the loop cycle to the beginning of text.
  
    return ''.join(result)     
    #result will look like this:  [["T"], ["A"], ["C"]]  and you want ["TAC"].  ``.join() will do this for you.