Home > Software design >  Sorting integers by absolute value, weighting positive and negative
Sorting integers by absolute value, weighting positive and negative

Time:10-18

I am trying to create a code list that follows this parameter. This takes in an unsorted list and returns a sorted list according to the absolute sorting where the positive value will be considered smaller. The original list which is passed in should be unchanged. below is what i have so far how do i switch the numbers in the list.

n = int(input("Enter number of elements : "))

list_1 = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
print("\nList is - ", list_1)
def absolute_value(num):
    return abs(num)


list_2 = list_1.sort(key = absolute_value)
print(list_2)
def length_of_list(list_2):
    for i in list_2:
        for j in list_2:
            if abs(i) == abs(j) and i < j:

CodePudding user response:

This almost does what you need:

xs = [-3, -2, -1, 0, 1, 2, 3]
xs.sort(key=abs)
print(xs)

But the positive numbers can end up after the negative ones:

[0, -1, 1, -2, 2, -3, 3]

If you want the negative values to always end up after the positive ones, this is one way to do it:

def sort_val(x):
    return abs(x)*2   int(x < 0)  # e.g. -3 becomes 7, 3 becomes 6

xs = [-3, -2, -1, 0, 1, 2, 3]
xs.sort(key=sort_val)
print(xs)

Result:

[0, 1, -1, 2, -2, 3, -3]

CodePudding user response:

You need to know the index of the list that you want to change, to do this you can use the enumerate functions

...
if abs(i) == abs(j) and i < j:
    list_2[idx1], list_2[idx2] = list_2[idx2], list_2[idx1]
  • Related