3
votes

I'm stuck at an exercise where I need to reverse a random string in a function using only a loop (for loop or while?).

I can not use ".join(reversed(string)) or string[::-1] methods here so it's a bit tricky.

My code looks something like this:

def reverse(text):
    while len(text) > 0:
        print text[(len(text)) - 1],
        del(text[(len(text)) - 1]

I use the , to print out every single letter in text on the same line!

I get invalid syntax on del(text[(len(text)) - 1]

Any suggestions?

4
Are you trying to reverse the string or print the characters in reverse order? Your title implies the former but your code seems to be trying to do the latter. If you want to reverse the string -- build it up and then return the reversed string. Let the calling code print it if it wants. Most functions shouldn't have print in them. - John Coleman
You could use a temp variable to build the reversed string instead of manipulating the original string - Mike Scotty
del modifies an object, but you cannot modify a string, you must create a new string instead. Try creating a new string with one character fewer: text = text[:-1] - Duncan
@Duncan true enough -- but pointless. OP has no good reason for trying to make the string smaller in the course of building up the reverse. - John Coleman
@Duncan I wouldn't say that a quadratic algorithm for reversing a string is perfectly valid, although it is of course valid. Creating a copy of the string at each stage is expensive. - John Coleman

4 Answers

4
votes

The problem is that you can't use del on a string in python. However this code works without del and will hopefully do the trick:

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

print(reverse("Hello World!")) # prints: !dlroW olleH
6
votes

Python string is not mutable, so you can not use the del statement to remove characters in place. However you can build up a new string while looping through the original one:

def reverse(text):
    rev_text = ""
    for char in text:
        rev_text = char + rev_text
    return rev_text

reverse("hello")
# 'olleh'
1
votes

Python strings are immutable. You cannot use del on string.

text = 'abcde'
length = len(text)
text_rev = ""
while length>0:
   text_rev += text[length-1]
   length = length-1

print text_rev

Hope this helps.

0
votes

Here is my attempt using a decorator and a for loop. Put everything in one file.

Implementation details:

def reverse(func):
    def reverse_engine(items):
        partial_items = []
        for item in items:
            partial_items = [item] + partial_items
        return func(partial_items)
    return reverse_engine

Usage:

Example 1:

@reverse
def echo_alphabets(word):
    return ''.join(word)

echo_alphabets('hello')
# olleh

Example 2:

@reverse
def echo_words(words):
    return words

echo_words([':)', '3.6.0', 'Python', 'Hello'])
# ['Hello', 'Python', '3.6.0', ':)']

Example 3:

@reverse
def reverse_and_square(numbers):
    return list(
        map(lambda number: number ** 2, numbers)
    )

reverse_and_square(range(1, 6))
# [25, 16, 9, 4, 1]