7/15 I want a critic on my way to solve it


#1

So here is the code:

def reverse(x):
new_reverse = ""
new_list = []
for i in range(len(x)):
letter = x[i]
new_list.insert(len(x),str(letter))
for n in range(len(new_list)):
new_location = len(new_list) - n - 1
new_reverse += new_list[new_location]
return new_reverse

print reverse("Python!")

what you would have done different?
EDIT: Ugh... for some reason I can't edit my code for it to be with the right blocks... so just imagine that all of the code is a block in def and every for loop is open another block (I mean the for loops are on the same block)


#2

You kinda are doing a little too much to get your results.

You can easily do it by just flipping the index position around.

def reverse(text):
    return ''.join(text[-(index + 1)] for index, letter in enumerate(text))

By using enumerate we are able to get the index returned at the same time as we iterate over the string. This allows us to flip it easily to go backwards through our string.


#3

What does -X in index means? I am a Python newbie :smiley:


#4

Same thing as it does in math, if you put a number in parentheses and then add a - to the front.

It simply changes it to a negative value because it multiplies it by an implied negative one.


#5

well yea, but what's the logic in Python? I mean does it automatticly count from the last?
Like, -1 is the last letter?


#6

If you read what I have posted,

I am using the string method join, then I am passing it a generator which will iterate through an item given to it.

The item in question here is the text passed to the function, and because I am accessing the index of the iterator as I iterate with enumerate I can use the index on the string pass into the loop.

Doing this I can add one to offset for zero counting and then flip it to a negative so that it counts from the end because when you access an item through an index if you pass a negative number it access it from the end towards the front end.

-----------------------------------------------
  A|  B| C| D| E| F| G| H| I| J|K
-----------------------------------------------
  0|  1| 2| 3| 4| 5| 6| 7| 8| 9|10
-11|-10|-9|-8|-7|-6|-5|-4|-3|-2|-1
-----------------------------------------------

Now looking at the above indexing we can see if we pass the function ABCDEFGHIJK as an argument it will indeed give us back `KJIHGFEDCBA'.

Now if we access the index of the argument ourselves at position 5 it will give us the letter F in order to get the same thing with a negative index we need to pass it -6. By using this simple logic we can use it to reverse anything in python that we can access by index.


#7

Here's the code I used:

 def reverse(text):
     b = ""
     for letter in text:
         b = letter + b
         
     return b

Basically it checks for every letter in the text and adds it to the beginning of the new variable called b.
This makes b the reverse of the text.