DEV Community

Discussion on: Interview Qs Decoded - # 2

Collapse
 
hammertoe profile image
Matt Hamilton

In Python:

More verbose using a for loop:

def revFunction(str):
  arr = []
  for i in range(len(str)):
    arr.append(str[-i-1])
  return ''.join(arr)

More concise, using a list comprehension:

def revFunction(str):
  return ''.join([str[-i-1] for i in range(len(str))])
Collapse
 
cat profile image
Cat

Yesss I was waiting for a Python response!!!

Collapse
 
hammertoe profile image
Matt Hamilton

Actually just realised an even more concise way in Python. The slice operator takes a step as an optional 3rd argument, and I just found out the step can be negative.

>>> str = "Reverse me!"
>>> str[::-1]
'!em esreveR'

So...

def revFunction(str):
  return str[::-1]