Search This Blog

Handon - Python - slicing-- HackerRank Questions and answers Course ID:55193

 Python - Slicing

Pramodh is a friend of Azar, Who joined newly to 'xyz' computer coaching center. He wants to learn a concept called slicing in python. Let's help him to understand the concept called 'slicing'.

Function 'sliceit' takes a parameter called 'mylist' as a list. 'mylist' contains a list of elements. Slice the elements from the list based on the condition given below:

  • Print the second and third element from the 'mylist'.
  • Print the list of odd indexed elements of list 'mylist'. Since indexing starts at zero, odd indices would be 1,3 and so on.
  • Print the last three elements from the 'mylist' in a reverse manner.
Constraints:
  • 'mylist' should not contain more than 1000 elements
Input Format for Custom Testing:
Input from stdin will be processed as follows and passed to the function.

The first line contains an integer n, the size of the mylist.
Each of the next n lines contains an mylist[i] where 0<=i<n

Sample Case 0
Sample Input:

STDIN      Function Parameters 
-----      -------------------                         
8       →  mylist[] Size n = 8
3       →  mylist[] = [ 3, 4, 3, 2, 6, 1, 2, 6 ]
4
3
2
6
1
2
6

Sample Output
['4','3']
['4','2','1','6']
['6','2','1']



Answer:

#!/bin/python3

import math
import os
import random
import re
import sys


#
# Complete the 'sliceit' function below.
#
# The function accepts List mylist 
# as parameter.

#

def sliceit(mylist):
    # Write your code here
    print(mylist[1:3])
    print(mylist[1::2])
    print(mylist[-1:-4:-1])

if __name__ == '__main__':
    mylist_count = int(input().strip())

    mylist = []

    for _ in range(mylist_count):
        mylist_item = input()
        mylist.append(mylist_item)

    sliceit(mylist)






Click on the image to maximize:







No comments:

Post a Comment

If you have any doubts, Please let us know.