Home > Back-end >  Python insertion sort, sorting string and int
Python insertion sort, sorting string and int

Time:02-25

I'm trying to make program that sorts products that user inputs and i'm trying to achieve sorting strings ascending (name) and ints descending (code), any suggestions?

class Product:
  def __init__(self, name, code):
    self.name = name
    self.code = code


def insertion_sort(arr):
    for i in range(1, len(arr)):
        z = arr[i]
        j = i-1
        while j >= 0 and z < arr[j]:
            arr[j 1] = arr[j]
            j -= 1
        arr[j 1] = z
    return arr

l = []
p1 = Product('Product1', 2222888)
p2 = Product('NewProduct', 123333)
p3 = Product('Product', 9999999)
p4 = Product('Product1', 2222887)
p5 = Product('TestProduct', 6281732)
l.append([p1.name, p1.code])
l.append([p2.name, p2.code])
l.append([p3.name, p3.code])
l.append([p4.name, p4.code])
l.append([p5.name, p5.code])

print(insertion_sort(l))

CodePudding user response:

You can use the python function sorted for this purpose

You will need to provide key for sorting

Here is the updated code.

class Product:
    def __init__(self, name, code):
        self.name = name
        self.code = code


l = []
p1 = Product('Product1', 2222888)
p2 = Product('NewProduct', 123333)
p3 = Product('Product', 9999999)
p4 = Product('Product1', 2222887)
p5 = Product('TestProduct', 6281732)

srted = sorted([p1, p2, p3, p4, p5], key=lambda x: (x.name, -x.code))
print([(i.name, i.code) for i in srted])

the key function returns tuple of x.name and -x.code.

so when the x.name of both object is same it checks the -x.code which is negative so product objects will be sorted in descendent manner which have the same x.name

  • Related