Home 01. Arrays - DS
Post
Cancel

01. Arrays - DS

Problem: Arrays - DS

Solution 1: Using for loop and storing in another array

1
2
3
4
5
def reverseArray(a):
    arr = []
    for i in range(len(a) - 1, -1, -1):
        arr.append(a[i])
    return arr

Solution 2: Using for loop

1
2
def reverseArray(a):
    return [a[i] for i in range(len(a) - 1, -1, -1)]

Solution 3: Using loop and slicing

1
2
def reverseArray(a):
    return [a[i] for i in range(len(a))[::-1]]

Solution 4: Using list comprehension and reversed() function

1
2
def reverseArray(a):
    return [a[i] for i in reversed(range(len(a)))]

Solution 5: Using reversed() function

1
2
def reverseArray(a):
    return list(reversed(a))

Solution 6: Using for loop and if-else statement

1
2
def reverseArray(a):
    return [a[-1*(i+1)] for i in range(len(a))]

Solution 7: Using Slicing

1
2
def reverseArray(a):
    return a[::-1]

Solution 8: Using reverse() function

1
2
3
def reverseArray(a):
    a.reverse()
    return a

Method #9: the Bad

1
2
3
4
5
def reverseArray(a):
	rev_a = list()
	for val in a:
		rev_a = [val] + rev_a
	return rev_a

Method #10: the Good

1
2
3
4
5
def reverseArray(a):
    rev_a = []
    for val in a:
        rev_a.insert(0, val)
    return rev_a

Method #11: the Better

1
2
def reverseArray(a):
    return [a.pop() for t in range(len(a))]
This post is licensed under CC BY 4.0 by the author.

1. Introduction to Linked List

Learn Data Science step by step