Problem 4: Reverse (50pts)
Problem
my_reversetakes in a listland returns a new list that contains exactly the same elements inlbut in the reverse order.
my_reverse 接受一个列表 l,并返回一个包含与 l 中完全相同的元素但顺序相反的新列表。
def my_reverse(l):
"""Returns a new list that contains the exact same elements in l with reversed order.
>>> a = ['S', 'I', 'C', 'P']
>>> a is my_reverse(a) # the returned list is newly created
False
>>> my_reverse(my_reverse(a)) == a # reverse twice equals to the original list
True
>>> my_reverse(a)
['P', 'C', 'I', 'S']
>>> a
['S', 'I', 'C', 'P']
"""
"*** YOUR CODE HERE ***"
Hints
Hint: use clever slicing.
-
使用巧妙的切片(slicing)。
-
切片能接受三个参数,想想怎么用第三个参数。
Solutions
使用切片,step = -1。
def my_reverse(l):
return l[::-1]