Samantha Shaffer1,710 Points
I think I have the right answer...but the program says I'm wrong. Help!
I need to return a list in reverse only showing every other value. I create "reverse_evens" below to do so and when I test it, it seems to work. But the program says I'm wrong.
def first_4(x): return x[:4] def first_and_last_4(x): return x[:4] + x[-4:] def odds(x): return x[1::2] def reverse_evens(x): return x[::-2]
Hey Samantha, the reason why your code may seem to work correctly when you test it but then it fails the code challenge is that the code challenges are running tests that give your code a bunch of different inputs to see if it works under all circumstances. The code you have written might work for some circumstances, but still fail a few of the tests. Hope that makes sense! Now moving on to your code.
This challenge is not really asking you to return a slice that contains every other item in the iterable. What it is actually asking you to do is return a slice containing all the items in the argument that occupy an even index value, but in reverse. So there are two steps here.
- Let's not worry about the reverse part of this challenge right now. Problem-solving is about solving one piece of the puzzle at a time. How do you get all the even items in an iterable? Try it yourself first, then look at my answer.
iterable[::2]. This returns a slice that starts at the beginning, goes to the end, and returns every second item.
- Now, how do you return a slice that contains the reverse of an iterable? Slices are iterables themselves, so you can take a slice of a slice. Try it yourself.
Now put them together:
Hope this helps you solidify your knowledge of slices!