14.9k views
3 votes
The list method reverse reverses the elements in the list. Define a function named reverse that reverses the elements in its list argument (without using the method reverse!). Try to make this function as efficient as possible, and state its computational complexity using big-O notation.

User Slier
by
5.6k points

1 Answer

7 votes

Answer:

#code in python.

#function that reverse the element of list

def reverse(inp_lst):

for i in range(len(inp_lst)//2):

inp_lst[i], inp_lst[len(inp_lst) - i - 1] =inp_lst[len(inp_lst) - i - 1], inp_lst[i]

#main method

def main():

#create a list

lst1 = list(range(8))

print("list before revere:",lst1)

#call the method with list parameter

reverse(lst1)

print("list after revere:",lst1)

#create another list

lst2 = list(range(5))

print("list before revere:",lst2)

#call the method with list parameter

reverse(lst2)

print("list after revere:",lst2)

#call the main method

main()

Step-by-step explanation:

In main method, create a list and call the method revers() with the list parameter. In the revers() method, swap the first element with last and second with second last. Similarly loop will run half the length of list.This will reverse the elements of the list.Then print the list before and after the revers in the main .Similarly we can test it for another list.

As the loop run for n/2 time in the method reverse(), so the complexity of the code is O(n).

Output:

list before revere: [0, 1, 2, 3, 4, 5, 6, 7]

list after revere: [7, 6, 5, 4, 3, 2, 1, 0]

list before revere: [0, 1, 2, 3, 4]

list after revere: [4, 3, 2, 1, 0]

User Mckoss
by
5.2k points