Open In App

Python | Rearrange Positive and Negative Elements

Sometimes, while working with Python lists, we can have a problem in which we need to perform a sort in list. There are many variations of sorting that might be required to perform. Once such variation can be to sort elements of list, but keeping in mind, positive elements appear before negative elements. Let’s discuss a way in which this task can be performed. 

Method 1: Using sorted() + lambda 

This task can be performed using a combination of the above functions. In this, the logic we apply is computing the inverse and negative of each number and then performing the sort using sorted(). The inversion makes sure that larger magnitude elements occur in the middle and smaller at ends ( hill arrangement ) and the negative takes care of making positives occur before negatives. 




# Python3 code to demonstrate working of
# Sort while keeping Positive elements before negatives
# using sorted() + lambda
 
# initialize list
test_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Sort while keeping Positive elements before negatives
# using sorted() + lambda
res = sorted(test_list, key = lambda i: 0 if i == 0 else -1 / i)
 
# printing result
print("Result after performing sort operation : " + str(res))

Output
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]

Time complexity: O(nlog(n))
This is because the sorting algorithm used is QuickSort, which has a time complexity of O(nlog(n)). 

Auxiliary Space: O(n)
This is because we are creating a new list of the same size as the original list.

Method 2: Using sort() and extend() methods




# Python3 code to demonstrate working of
# Sort while keeping Positive elements before negatives
 
# initialize list
test_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Sort while keeping Positive elements before negatives
res1 = []
res2 = []
for i in test_list:
    if(i > 0):
        res1.append(i)
    else:
        res2.append(i)
res1.sort()
res2.sort()
res1.extend(res2)
 
# printing result
print("Result after performing sort operation : " + str(res1))

Output
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]

Time complexity: O(n log n) 
since it uses a sorting algorithm 

Auxiliary Space: O(n) 
since it uses an additional list to store the sorted elements

Method 3: Using the built-in filter() function along with a lambda function

Using the built-in filter() function along with a lambda function to separate the positive and negative elements in the list, and then using the built-in sort() function to sort the two lists separately. Then use the built-in extend() function to merge the two lists together.




# Python3 code to demonstrate working of
# Sort while keeping Positive elements before negatives
# using filter() + sorted() + + operator
 
# initialize list
test_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]
# printing original list
print("The original list is : " + str(test_list))
# Sort while keeping Positive elements before negatives
# using filter() + sorted() + + operator
res = sorted(filter(lambda x: x > 0, test_list)) + \
    sorted(filter(lambda x: x < 0, test_list))
# printing result
print("Result after performing sort operation : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy

Output
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]

Time Complexity: O(n log n)
Auxiliary Space: O(n)

Method 4: Using List comprehension

Using List comprehension, sort positive and negative separately and then concatenate the lists.




# Python3 code to demonstrate working of
# Sort while keeping Positive elements before negatives
# using list comprehension
 
# initialize list
test_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]
 
# printing original list
print("The original list is : " + str(test_list))
positive_nums = [x for x in test_list if x >= 0]
negative_nums = [x for x in test_list if x < 0]
positive_nums.sort()
negative_nums.sort()
res = positive_nums + negative_nums
# printing result
print("Result after performing sort operation : " + str(res))
 
# This code is contributed by vinay pinjala.

Output
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]

Time Complexity: O(n log n)
Auxiliary Space: O(n)

Method 5: Using two pointers and swapping

Approach:

  1. Initialize two pointers, left pointing to the first element of the list and right pointing to the last element of the list.
  2. Loop until left pointer crosses the right pointer:
    a. Check if the left element is negative and right element is positive, swap them.
    b. If the left element is positive, move the left pointer to the right.
    c. If the right element is negative, move the right pointer to the left.
  3. The list is sorted with positive numbers before negative numbers




# Python3 code to demonstrate working of
# Sort while keeping Positive elements before negatives
# using two pointers and swapping
 
# initialize list
test_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initialize two pointers, left pointing to the first element of the list and right pointing to the last element of the list
left, right = 0, len(test_list) - 1
 
while left <= right:
    # check if the left element is negative and right element is positive
    if test_list[left] < 0 and test_list[right] >= 0:
        # swap them
        test_list[left], test_list[right] = test_list[right], test_list[left]
    if test_list[left] >= 0# if the left element is positive, move the left pointer to the right
        left += 1
    if test_list[right] < 0# if the right element is negative, move the right pointer to the left
        right -= 1
 
# printing result
print("Result after performing sort operation : " + str(test_list))

Output
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [4, 5, 10, 3, 8, -5, -6, -8, -19]

Time complexity: O(n)
where n is the length of the list.
Auxiliary space: O(1)
As we are not using any extra space to store the elements.

Method 6:   Using itertools:

Algorithm:

  1. Initialize the list test_list
  2. Print the original list
  3. Create two sublists, one containing the positive elements and one containing the negative elements, using the filter function
  4. Sort the positive elements sublist in ascending order, using the sorted function
  5. Concatenate the two sublists using the + operator, with the positive elements sublist first
  6. Convert the resulting iterator into a list using the list function
  7. Print the sorted list




import itertools
 
test_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]
# printing original list
print("The original list is : " + str(test_list))
 
# Sort while keeping Positive elements before negatives
# using itertools.chain and itertools.filterfalse
res = list(itertools.chain(
sorted(filter(lambda x: x > 0, test_list)),
itertools.filterfalse(lambda x: x > 0, test_list)))
 
# printing result
print("Result after performing sort operation : " + str(res))
 
#This code is contributed by Rayudu.

Output
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -8, -6, -5, -19]

Time Complexity: O(n log n)
The time complexity of this code is O(n log n), where n is the length of the input list. This is because sorting the positive elements takes O(k log k) time, where k is the number of positive elements, and sorting the negative elements also takes O(m log m) time, where m is the number of negative elements. Since k + m = n, the overall time complexity is O(n log n).

Auxiliary Space: O(N)
The space complexity of this code is O(n), where n is the length of the input list. This is because the code creates two sublists to store the positive and negative elements separately, each with at most n elements. The space complexity does not depend on the values of the elements or their order. Additionally, the sorted function creates a new sorted list, which also takes up O(n) space. Finally, the + operator creates a new concatenated list, which again takes up O(n) space. Thus, the total space complexity is O(n).
 


Article Tags :