Sunday, November 17, 2024
Google search engine
HomeLanguagesLambda expression in Python to rearrange positive and negative numbers

Lambda expression in Python to rearrange positive and negative numbers

Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array. The order of appearance should be maintained. 

Examples:

Input :  arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6]
Output : arr[] = [-13, -5, -7, -3, -6, 12, 11, 6, 5]\
Input :  arr[] = [-12, 11, 0, -5, 6, -7, 5, -3, -6]
Output : arr[] =  [-12, -5, -7, -3, -6, 11, 0, 6, 5]

This problem has many solutions please refer Rearrange positive and negative numbers link, but we will solve this problem with single line of code in python using Lambda Expression

Implementation:

Approach:

  1. Define a function named “Rearrange” that takes an array “arr” as an argument.
  2. Use list comprehension to create two separate lists – one containing all negative elements in “arr” and another containing all non-negative (positive and zero) elements in “arr”.
  3. Concatenate the two lists in the order of negative elements first, followed by non-negative elements.
  4. Return the concatenated list.
  5. In the main section, create an array “arr” with some positive and negative numbers.
  6. Call the “Rearrange” function with “arr” as an argument.
  7. Print the returned list.

Python3




# Function to rearrange positive and negative elements
def Rearrange(arr):
 
    # First lambda expression returns list of negative numbers
    # in arr.
    # Second lambda expression returns list of positive numbers
    # in arr.
    return [x for x in arr if x < 0] + [x for x in arr if x >= 0]
 
# Driver function
if __name__ == "__main__":
    arr = [12, 11, -13, -5, 6, -7, 5, -3, -6]
    print (Rearrange(arr))


Output

[-13, -5, -7, -3, -6, 12, 11, 6, 5]

Time Complexity: O(n)
We iterate over the list of elements once, so the time complexity is linear.

Space Complexity: O(n)
We create two temporary lists, so the space complexity is also linear.

This article is contributed by Shashank Mishra (Gullu). If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

RELATED ARTICLES

Most Popular

Recent Comments