Challenge - 5 Problems
Reversed Function Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
Output of reversed() on a string
What is the output of this Python code?
Python
s = 'hello' result = ''.join(reversed(s)) print(result)
Attempts:
2 left
๐ก Hint
reversed() returns an iterator that goes through the input backwards.
โ Incorrect
The reversed() function returns an iterator that yields characters from the string in reverse order. Joining these characters produces the reversed string.
โ Predict Output
intermediate2:00remaining
Using reversed() on a list
What is the output of this code snippet?
Python
lst = [1, 2, 3, 4] rev_lst = list(reversed(lst)) print(rev_lst)
Attempts:
2 left
๐ก Hint
reversed() works on any sequence, including lists.
โ Incorrect
reversed(lst) returns an iterator that goes through the list backwards. Converting it to a list shows the reversed order.
โ Predict Output
advanced2:00remaining
Output of reversed() on a dictionary keys view
What happens when you run this code?
Python
d = {'a': 1, 'b': 2, 'c': 3}
print(list(reversed(d.keys())))Attempts:
2 left
๐ก Hint
Check if dict_keys supports reversed() directly.
โ Incorrect
dict_keys objects do not support reversed() because they are not sequences and do not implement __reversed__.
โ Predict Output
advanced2:00remaining
Reversing a range object
What is the output of this code?
Python
r = range(1, 5) print(list(reversed(r)))
Attempts:
2 left
๐ก Hint
range objects support reversed() because they are sequences.
โ Incorrect
range(1, 5) generates numbers 1 to 4. reversed(range(1,5)) iterates backwards from 4 to 1.
๐ง Conceptual
expert3:00remaining
Behavior of reversed() on custom iterable
Consider this class:
class CountDown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
What happens if you call reversed(CountDown(3))?
Attempts:
2 left
๐ก Hint
reversed() requires __reversed__ or __len__ and __getitem__ methods.
โ Incorrect
The CountDown class only implements __iter__, not __reversed__ or __getitem__, so reversed() cannot reverse it and raises TypeError.