7/15 Reverse


#1

Hi, this is my code:

import sys
def reverse(text):
  text = str(text)
  holder = []
  for i in range(0,len(text)):
    holder.append(text[i])
  x = len(text) - 1
  while (x >= 0):
    sys.stdout.write(holder[x])
    x -= 1
  return

Why result of my program is --> cba!nohtyP <-- ?
From where is ‘cba’?


#2

different test cases/function calls from the exercise validition.


#3

So what can I do now? I can’t finish this exercise:

Your function fails on reverse(“Python!”). It returns “None” when it should return “!nohtyP”.


#4

You could change the return statement so that the reverse string is returned and not None.


#5
import sys
def reverse(text):
  text = str(text)
  holder = []
  for i in range(0,len(text)):
    holder.append(text[i])
  x = len(text) - 1
  while (x >= 0):
    # print holder[x],
    sys.stdout.write(holder[x])
    x -= 1
  return "!nohtyP" 

OK, I modify return, but now i have next problem:

Your function fails on reverse(“coolstory”). It returns “!nohtyP” when it should return “yrotslooc”.


#6

Why return a fixed string? The great thing of a function is that its capable of reversing multiple strings (by passing different strings as argument on function call), so the string you reverse should be returned.

For example:

import sys
def reverse(text):
  text = str(text)
  holder = []
  for i in range(0,len(text)):
    holder.append(text[i])
  x = len(text) - 1
  while (x >= 0):
    # print holder[x],
    sys.stdout.write(holder[x])
    x -= 1
  return "!nohtyP" 

reverse("coolstory")
reverse("abc")

your function returns !nohtyP even though we want the reverse of coolstory and abc


#7

Everything works, thanks :sunglasses:


#8

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