Works, but CC fails it


#1

I’m testing following code on python 2.7 and it works. But Code Academy fails this code.
Could you explain why?

def reverse(x):
return [ x[i * -1] for i in range(1, len(x) + int(1)) ]


FAQ: Learn Python - Practice Makes Perfect - reverse
FAQ: Learn Python - Practice Makes Perfect - reverse
#2

Does the exercise instruct to return a string, in reverse of the input? The above returns a list.

Another concern is that it uses a concept (comprehension) that is not introduced until the Advanced Topics unit. Clearly the author believes we still have enough tools to complete this task.

Not sure what effect is expected? Is 1 not already an integer?

Say we want your code to return a string, the advanced nature of list comprehension aside. Have we by this point learned about the join() method?

For simplicity, consider that,

i * -1  ==  -i

so that,

>>> x = "Python is fun!"
>>> [x[-i] for i in range(1, len(x) + 1)]
['!', 'n', 'u', 'f', ' ', 's', 'i', ' ', 'n', 'o', 'h', 't', 'y', 'P']
>>> ''.join([x[-i] for i in range(1, len(x) + 1)])
'!nuf si nohtyP'
>>> 

This should be sufficient to pass the lesson check if in fact a string return is expected.

Define a function called reverse that takes a string text and returns that string in reverse. For example: reverse("abcd") should return "dcba" .

You may not use reversed or [::-1] to help you with this.

Given that slicing and the built-in function are disallowed, the above is more than a leap forward, but is on the right track… Negative indices.

How do we get this into basic form without the comprehension?

>>> y = ''
>>> for i in range(1, len(x) + 1):
	y += x[-i]

	
>>> y
'!nuf si nohtyP'
>>> 

Can we remove some of the ambiguity by generating a reversed range such that,

y += x[i - 1]

?

# range (start, stop, step)
>>> range(len(x), 0, -1)
[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> y = ''
>>> for i in range(len(x), 0, -1):
	y += x[i - 1]

	
>>> y
'!nuf si nohtyP'
>>> 

Notice that now the index is positive, but the stride is negative?


#3

Thank you for great explanation!


#4

You’re welcome!

Be sure to drill into every aspect of the range() function in your review study.


#5

I was able to generate the correct answer, but CC fails it. why?

new =
def reverse(text):
index = len(text) -1
while index >= 0:
new.append(text[index])
index -= 1
return ‘’.join(new)

print reverse(‘poo’)


#6

Creating the list outside of the function means it can never be reset. Declare the array inside the function so it starts fresh on each new call.