Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDiane Blamaud
4,166 PointsTask 4/4, function works when tested on python shell but isn't accepted as a correct answer to pass the challenge
''' def reverse_evens(iterable): return iterable[::-2] ''' This functions returns [5, 3, 1] when passed the example [1, 2, 3, 4, 5] in python shell but isn't accepted on the challenge page. Therefore I cannot determine where the mistake is. Can someone see where the mistake might be?
def first_4(iterable):
return iterable[:4]
def first_and_last_4(iterable):
return iterable[:4] + iterable[-4:]
def odds(iterable):
return iterable[1::2]
def reverse_evens(iterable):
return iterable[::-2]
1 Answer
Kip Yin
4,847 PointsThe problem is that your code (iterable[::-2]
) only works when the length of the iterable is odd.
The first thing comes to me is using a conditional:
def reverse_evens(iterable):
return iterable[-2::-2] if len(iterable) % 2 == 0 else iterable[::-2]
or if you prefer:
def reverse_evens(iterable):
if len(iterable) % 2 == 0:
return iterable[-2::-2]
else:
return iterable[::-2]
Kip Yin
4,847 PointsKip Yin
4,847 PointsJust for fun, the solution can be even shorter:
Diane Blamaud
4,166 PointsDiane Blamaud
4,166 PointsOhh I hadn't thought about this! I wasn't testing it enough. Thanks!
Kip Yin
4,847 PointsKip Yin
4,847 PointsNo problem! If the answer is helpful, a "Best Answer" would be appreciated. Good luck on learning!
Idris Abdulwahab
Courses Plus Student 2,961 PointsIdris Abdulwahab
Courses Plus Student 2,961 PointsAlthough this was not posted by me but I really benefited from the insight and hints. Thank you Kip.
Kip Yin
4,847 PointsKip Yin
4,847 PointsI'm glad it helped!