Lambda expression in Python to rearrange positive and negative numbers
Last Updated :
27 Mar, 2023
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:
- Define a function named “Rearrange” that takes an array “arr” as an argument.
- 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”.
- Concatenate the two lists in the order of negative elements first, followed by non-negative elements.
- Return the concatenated list.
- In the main section, create an array “arr” with some positive and negative numbers.
- Call the “Rearrange” function with “arr” as an argument.
- Print the returned list.
Python3
<div id = "highlighter_261585" class = "syntaxhighlighter nogutter " ><table border = "0" cellpadding = "0" cellspacing = "0" ><tbody><tr><td class = "code" ><div class = "container" ><div class = "line number1 index0 alt2" ><code class = "comments" >
|
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.
Share your thoughts in the comments
Please Login to comment...