Answer to Question #265972 in Python for Siddu

Question #265972

You are given a space separated list of integers as input, write a program to replace all non positive numbers in a list with the last positive number encountered

1
Expert's answer
2021-11-15T00:23:04-0500

def rightRotate(arr, n, outOfPlace, cur):

  temp = arr[cur]

  for i in range(cur, outOfPlace, -1):

    arr[i] = arr[i - 1]

  arr[outOfPlace] = temp

  return arr

 

 

def rearrange(arr, n):

  outOfPlace = -1

  for index in range(n):

    if(outOfPlace >= 0):

 

       

      if((arr[index] >= 0 and arr[outOfPlace] < 0) or

        (arr[index] < 0 and arr[outOfPlace] >= 0)):

        arr = rightRotate(arr, n, outOfPlace, index)

        if(index-outOfPlace > 2):

          outOfPlace += 2

        else:

          outOfPlace = - 1

 

    if(outOfPlace == -1):

 

      # conditions for A[index] to

      # be in out of place

      if((arr[index] >= 0 and index % 2 == 0) or

        (arr[index] < 0 and index % 2 == 1)):

        outOfPlace = index

  return arr

 

 

#here you can add you input numbers

arr = [-1, 2, -5, -2, 4,

    -8, 1, 9, 0, 8]

 

print("Given Array is:")

print(arr)

 

print("\nRearranged array is:")

print(rearrange(arr, len(arr)))

 

#This code considered by expert Suhrob Umarov


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS