If someone can point out the flaw here


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/reverse?action=lesson_resume

This doubt is with respect to the Python learning track. More specifically the ‘Practice Makes Perfect - Reverse’ exercise.
I wrote a code to execute the required switches in index, but my code isn’t functioning well. It seems to give the correct output if I enter odd character strings but not with even character strings. The code relies on evaluating the mean of the indices, the difference of index from the mean, and then adding/subtracting (based on whether the original index is above or below the mean) that difference to the mean to get the required reversed index. I would be grateful if someone can point out the flaw here. Thanks

def reverse(text):
  l = range(len(text))
  mean = sum(l)/len(text)
  for i in l:
    if i<mean:
      x=mean+abs(mean - i)
      print text[x],
    else:
      x= mean - abs(mean -i)
      print text[x],

#2

i think you should start over, using mean sounds like a bad idea

there are two common approaches:

loop over the string in reverse and append to new list/string
prepend the characters to a new string/list

both will cause the string to reverse

using print with , won’t do, you need to return the reversed string, so you need to create a string which will contain the reversed string


#3

Could there be some confusion between mean and median?

Consider the following JavaScript example that uses a similar approach to reverse an array in place…

const reverseArrayInPlace = arr => {
  let n = arr.length;
  let m = parseInt(n / 2);
  let temp;
  if (n % 2) {
    for (let i = 0; i < m; i++) {
      temp = arr[m - i - 1];
      arr[m - i - 1] = arr[m + i + 1];
      arr[m + i + 1] = temp;
    }
  } else {
    k = m - 1;
    for (let i = 0; i < m; i++) {
      temp = arr[k - i];
      arr[k - i] = arr[m + i];
      arr[m + i] = temp;
    }
  }
}
let arr;
arr = [1,2,3,4,5,6,7]; reverseArrayInPlace(arr); console.log(arr);
arr = [1,2,3,4,5,6,7,8]; reverseArrayInPlace(arr); console.log(arr);
[ 7, 6, 5, 4, 3, 2, 1 ]
[ 8, 7, 6, 5, 4, 3, 2, 1 ]

https://repl.it/LNV3/0


#4

I found an easier way as well

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

Thanks for the help !


#5

I appreciate the effort to help out, but I don’t know JavaScript so this doesn’t provide much assistance to me. In any case, I found a different method to get through this exercise.Thank You!


#6

There is not much difference between the two languages. The meat of the example is nearly identical to a Python version. In my view, you should not abandon your earlier approach without solving it first. The goal in this exercise is not to seek out the easiest or best, but to stretch our imaginations and try out lots of approaches.

def reverseArrayInPlace(arr):
  n = len(arr)
  m = int(n / 2)
  temp = 0
  if n % 2:
    for i in range(m):
      temp = arr[m - i - 1]
      arr[m - i - 1] = arr[m + i + 1]
      arr[m + i + 1] = temp
  else:
    k = m - 1
    for i in range(m):
      temp = arr[k - i]
      arr[k - i] = arr[m + i]
      arr[m + i] = temp
  return arr

array = [1,2,3,4,5,6,7]; reverseArrayInPlace(array); print(array);
array = [1,2,3,4,5,6,7,8]; reverseArrayInPlace(array); print(array);

https://repl.it/L5iw

In Python we call them lists, in JS we call them arrays. Same basic object… an indexed iterable.

To further my earlier point,

return arr[::-1]

is the easiest way. But what does that add to our experience journal? Only plying with ideas will truly expand the mind. Understanding always comes after many attempts and failure. In programming we expect things not to work, and when they do, we work even harder to break them. Success is built on failure.


#7

Your point makes sense. I got rid of the print with ,
But the problem persists… It does not work with even number of characters, but works perfectly for strings with odd number of characters. I am almost entirely sure that this is because the mean in an even number of consecutive integers does not belong to the set itself, but in the case of odd number of consecutive integers, it does. I shall keep trying nevertheless.


#8

I DID IT! YOU’RE AWESOME MAN, THANKS FOR THE LITTLE MOTIVATION THAT I NEEDED!
My logic was ok, except while evaluating the mean in the case of even number of consecutive integers, Python was rounding off my floats to integer values so there was always an error in strings with even characters. I wrapped my mean around in a float() and it worked perfectly.

I need more people like you around me bro.

def reverse(text):
l = range(len(text))
k = ""
mean = float(sum(l))/float(len(text))
for i in l:
if i<mean:
x=mean+abs(mean - i)
x=int(x)
else:
x= mean - abs(mean -i)
x=int(x)
k = k+text[x]
return k


#9

That’s great that you kept at it. Believe it or not that was the first thing I was going to suggest but opted not to, in favor of you discovering via a foreign example.

Here is another slightly more Pythonic revision of the code ported from JS…

def reverseListInPlace(lst):
  n = len(lst)
  m = int(n / 2)
  if n % 2:
    for i in range(m):
      lst[m - i - 1], lst[m + i + 1] = lst[m + i + 1], lst[m - i - 1]
  else:
    k = m - 1
    for i in range(m):
      lst[k - i], lst[m + i] = lst[m + i], lst[k - i]
  return lst

def reverseString(string):
  return ''.join(reverseListInPlace(list(string)))

a_list = [1,2,3,4,5,6,7]
reverseListInPlace(a_list)
print(a_list)
#-> [7, 6, 5, 4, 3, 2, 1]
a_list = [1,2,3,4,5,6,7,8]
reverseListInPlace(a_list)
print(a_list)
#-> [8, 7, 6, 5, 4, 3, 2, 1]
print (reverseString("Success is going from one failure to another without losing enthusiasm - W. Churchill"))
#-> llihcruhC .W - msaisuhtne gnisol tuohtiw rehtona ot eruliaf eno morf gniog si sseccuS

https://repl.it/L5iw/1

Happy coding!


Delving further into the in-place concept, we boil it down to this,

def reverse(text):
  text = list(text)
  for x in range(int(len(text) / 2)):
    y = -1 - x
    text[x], text[y] = text[y], text[x]
  return ''.join(text)

print (reverse("Python!"))
#-> !nohtyP

#10

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