Computer Science, asked by gautam344, 10 months ago

Python - write a program ti shift a list in two halfs . Show output as examples.

Answers

Answered by manavjaison
1

Heya friend !

Here's the source code for your program :-

#shifting a list into first half and second half

a = eval(input('Enter the list:'))

l=len(a)

if l%2!=0:

   j = l//2 + 1

   for i in range (l//2):

        a[i] , a[j] = a[j] , a[i]

        j+=1

    print('List after shifting it into two halves is:',a)

else:

   j=l//2

   for i in range (l//2):

        a[i] , a[j] = a[j] , a[i]

        j+=1

        print ('List after shifting it into two halves is:',a)

                             OUTPUT

1)

Enter the list : [1,2,3,4,5]

List after shifting it into two halves is: [4,5,3,1,2]

2)

Enter the list: [1,2,3,4]

List after shifting it into two halves is: [3,4,1,2]

                           EXPLANATION

  • Here, we have got separate loops for lists having odd and even number of elements because in case of list with odd number of elements, the middle - most element has to remain in it's own position.
  • Keep in mind the indentation of the program.

Thanks !

#BAL #answerwithquality

Similar questions