user10926213
user10926213

Reputation:

Print array elements in reverse order

The first line contains an integer N, (the size of our array). The second line contains N space-separated integers describing array's(A's) elements.

I have tried the following, however I looked at the solution page. However I do not understand how this code works. Can someone please explain it to me. I am pretty new in this coding world.

import math
import os
import random
import re
import sys

if __name__ == '__main__':
    n = int(input())
    arr = [int(arr_one) for arr_one in input().strip().split(' ')]
    for i in range(len(arr)):
        print(str(arr[-i-1]), end = " ")

input 1234 output 4 3 2 1

Upvotes: 1

Views: 3474

Answers (5)

Biman Pal
Biman Pal

Reputation: 439

In Python3:

if __name__ == '__main__':
    n = int(input())
    arr = list(map(int, input().rstrip().split()))
    print(" ".join(str(x) for x in arr[::-1]))

Input:

1 4 3 2

Output:

2 3 4 1

Upvotes: 2

Arunkumar Chinthapalli
Arunkumar Chinthapalli

Reputation: 351

Let's take this code snippet

n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
    print(str(arr[-i-1]), end = " ")

The method input() will take the user input from key board. int(input()) will convert the input into int, if the input is in string format. like "4" instead of 4. The input value stored into variable n.

The Array input will be like this "1 2 3 4". So, we need to separate the string with space delimiter.

The strip() method returns a copy of the string with both leading and trailing characters removed.

The split() method returns a list of strings after breaking the given string by the specified separator.Here the separator is space. So, split(' ')

input().strip().split(' ') will take "1 2 3 4" as input and the output is "1" "2" "3" "4".

Now we need to take each element after separated. And then covert into int and store into array.

arr = [int(arr_one) for arr_one in input().strip().split(' ')]

arr_one is a variable, this variable stores each element after split. For each element, we converted it into int and then storing into a array arr.

In python, array index start from 0. If we want to access from last index in the array, the index will start from -1, -2, -3, and so on.

for i in range(len(arr)): The for loop will iterate from index 0 to length of the array. in this example, size is 4. printing array elements from index -1. and the end argument is used to end the print statement with given character, here the end character is " ". So the output will be 4 3 2 1.

Upvotes: 0

Muhammad Haseeb
Muhammad Haseeb

Reputation: 644

Try this!

if __name__ == '__main__':
n = int(input()) # input as int from stream
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
"""
1. asking for input from user
2. strip() function removes  leading and trailing characters.
3. split(' ') function split your input on space into list of characters
4. arr_one variable contains yours splited character and your iterating over it using for loop
5. int(arr_one) converts it into integer and  [] is nothing just storing everything into another list.
6. In last you are assigning new list to arr variable
"""
for i in reversed(arr): # loop over list in reverse order with built in fucntion
    print(i, end = " ") # printing whatever comes in i

It should work like this:

3 # your n 
1 2 3 # your input
3 2 1 # output

Upvotes: -1

taurus05
taurus05

Reputation: 2546

You are creating a list of integer values, by removing spaces and splitting the values at ' '. After obtaining the list of integers, you are iterating over the list and converting the ith element from the back (a negative value of index denotes element with ith index from right and it is 1 based) of arr back to string and printing the number.

Example:

 arr = [1,2,3,4]
 print(arr[1])  #prints 2 on the console, i.e 2nd element from the left.
 print(arr[-1]) #prints 4 on the console, i.e 1st element from the right.

Upvotes: 1

Mithilesh_Kunal
Mithilesh_Kunal

Reputation: 929

The above code can be rewritten as below with more readability.

if __name__ == '__main__':
    n = int(input())
    inp = input("Enter the numbers seperated by spaces:::")
    inp = inp.strip() # To remove the leading and trailing spaces
    array = []
    for item in inp.split(' '):     # Splitting the input with space and iterating over each element
        array.append(int(item))     # converting the element into integer and appending it to the list

    print(array[::-1])  # here -1 says to display the items in the reverse order. Look into list comprehension for more details

For more details on list slicing, look in the python documentation.

Upvotes: -1

Related Questions