Q#12: Reverse It
Suppose you’re given an array of strings, s. Write a function using Python to take each string in the array and reverse it.
For example:
#Given the following:
s = [‘rac’, ‘talf’, ‘tot’, ‘tob’]
#Your function should return:
[‘car’, ‘flat’, ‘tot’, ‘bot’]
-Question from erik@interviewqs.com
TRY IT YOURSELF
Answer:
This question tests your python skills, specifically looping through a list and slicing strings. We will cover two possible answers, one using standard procedures and one with List Comprehension.
The standard way involves looping through the list, and using our knowledge of slicing where list[<start>:<end>:<by>] can be used with the <by> being -1, meaning we reverse our list. Recall if you use just the semicolon the indexes will be assumed to be the first through last item in the list.
ans = []
for i in s:
ans.append(i[::-1])
The other method is to use List Comprehension. Recall list comprehension works as follows list[expression(i) for i in list].
s= [i[::-1] for i in s]