Python Python Collections Slices Slice Functions

Sandy Leon
Sandy Leon
2,246 Points

Solution to problem does not work

I've tested the solution to this problem like 20 times in IDLE just to make sure I wasn't going crazy, I am entering the correct solution to part 4 of the slices.py challenge, but it keeps saying that the answer is wrong. Any help here would be greatly appreciated!

slices.py
def first_4(iterable):
    return iterable[0:4]

def first_and_last_4(iterable):
    fal = iterable[:4] + iterable[-4:]
    return fal

def odds(iterable):
    return iterable[1::2]

def reverse_evens(iterable):
    return iterable[::-2]

1 Answer

William Ennals
William Ennals
6,160 Points

Your solution will only work if the length of the iterable is an odd number. If the length of the iterable is an even number, the index's returned in your solution would all be odd. Remember, indexes start from 0. I used an if-else statement to modify the code for both scenarios as shown: def reverse_evens(iterable): if len(iterable)%2 == 0: #since this list is even, the index for the last number will be odd #for example an iterable with a length of 20, the index for the last digit will be 19, #which is odd, so we have to skip #that one return iterable[-2::-2] else: #since this list is odd, the index for the last number will be even #for example an iterable with a length of 19 the index for the last digit
# will be 18 which is odd, so we'll start from the end return iterable[-1::-2]

Sandy Leon
Sandy Leon
2,246 Points

Ohhh ok, gotcha! Thank you for your thorough explanation!