Arrays-DS| Array
TASK(easy)
An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, (where 0<i<N), that can be referenced as Ai or A[i].
Reverse an array of integers.
Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this.
Example
A=[1,2,3]
Return[3,2,1].
Function Description
Complete the function reverseArray in the editor below.
reverseArray has the following parameter(s):
- int A[n]: the array to reverse
Returns
- int[n]: the reversed array
Input Format
The first line contains an integer, N, the number of integers in A.
The second line contains N space-separated integers that make up A.
Constraints
1≤N≤103
1≤A[i]≤104 where A[i] is the integer in A.
Sample Input 1
Array=1 4 3 2
Sample Output 1
2 3 4 1
SOLUTION 1
def reverseArray(A):
# Reverse the list and return it
return A[::-1]
if __name__ == "__main__":
import sys
input = sys.stdin.read
data = input().split()
N = int(data[0]) # Read the number of integers
A = list(map(int, data[1:])) # Read the space-separated integers into a list
reversed_array = reverseArray(A) # Reverse the array
print(' '.join(map(str, reversed_array)))
SOLUTION 2
def reverseArray(A):
return A[::-1]
input_data = "1,4,3,2"
A = list(map(int, input_data.split(','))) # Convert the comma-separated string into a list of integers
reversed_array = reverseArray(A)
print(' '.join(map(str, reversed_array))) # Output: 2 3 4 1
Explanation Steps:
1.Function reverseArray(A):
- Takes a list A and returns it reversed using slicing [::-1].
2. Sample Input:
- input_data contains the input as a comma-separated string.
3. Parsing the Input:
- A = list(map(int, input_data.split(','))) splits the input string by commas and converts each element to an integer, resulting in a list of integers.
4. Reversing and Printing:
- reversed_array = reverseArray(A) reverses the list.
- print(' '.join(map(str, reversed_array))) converts the reversed list to a string of space-separated integers and prints it.