Reverser


#1

def reverse(n):
word = []
num=len(n)
for i in range(len(n)):
word+=n[(num-1)-i]
return word

Oops, try again. Your function fails on reverse("Python!"). It returns "['!', 'n', 'o', 'h', 't', 'y', 'P']" when it should return "!nohtyP".

Does anybody knows how I could join the characters with in the list.


#2

word[0] + word[1] + etc.

A for loop sounds best.
for x in word:
word[x] + word[x] + etc.


#3

@javascriptjoee He already did it with a for loop.
@systemslayer47474 Why are you using a list to do this? Empty string could be a better idea.


#4

Instead of making word an array, you can make it an empty string.

def reverse(text):
word = ""
num = len(text)
for i in range(num):
word += text[(num - 1) - i]
return word


#5

Thanks. I solved it using list... but the way you did it is better.


#6

to whom refers you?

blogninja80467 solution is simple code, but there is one huge problem:

strings are immutable in python, meaning every time you append to a string:

word += text[(num - 1) - i]

a new string is created with the combined result. So using a list (which is mutable) is much more efficient.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.