0

I have this code that sorts 3 coordinates by descending order of their y-coordinate but I feel that the same problem can be solved with much less code. Can someone help me optimize it?

import time

coord1 = [500, 0]
coord2 = [750, 5]
coord3 = [120, 1]

start = time.time()

if coord1[1] > coord2[1] and coord1[1] > coord3[1]:
    print('First is coord1:',coord1)
    if coord2[1] > coord3[1]:
        print('Second is coord2:',coord2)
        print('Third is coord3:',coord3)
    else:
        print('Second is coord3:',coord3)
        print('Third is coord2,:',coord2)

elif coord2[1] > coord1[1] and coord2[1] > coord3[1]:
    print('First is coord2:',coord2)
    if coord1[1] > coord3[1]:
        print('Second is coord1:',coord1)
        print('Third is coord3:',coord3)
    else:
        print('Second is coord3:',coord3)
        print('Third is coord1:',coord1)

elif coord3[1] > coord1[1] and coord3[1] > coord2[1]:
    print('First is coord3:', coord3)
    if coord1[1] > coord2[1]:
        print('Second is coord1:',coord1)
        print('Third is coord2:',coord2)
    else:
        print('Second is coord2:',coord2)
        print('Third is coord1:',coord1)

end = time.time()

total = (end - start)
print('Total time taken:',total)

It works perfectly, results I get are:

First is coord2: [750, 5]
Second is coord3: [120, 1]
Third is coord1: [500, 0]

However time taken is 0.016 seconds, which might not seem like much however this is going to be part of a much bigger program that needs to work quickly and efficiently. I also feel that this is quite a lot of code to perform a rather small function, so if there is anyway I can shorten this, please let me know!

  • [coord1,coord2,coord3].sort(lambda x:x[1],reverse=True) ,see https://stackoverflow.com/questions/17555218/python-how-to-sort-a-list-of-lists-by-the-fourth-element-in-each-list – Peter Mølgaard Pallesen Jun 07 '19 at 06:57

1 Answers1

0
# -*- coding: utf-8 -*-
"""
Created on Fri Jun  7 12:22:23 2019

@author: jainil
"""

import time

coord1 = [500, 0]
coord2 = [750, 5]
coord3 = [120, 1]

start = time.time()

lista=[]
lista.append(coord1)
lista.append(coord2)
lista.append(coord3)
lista.sort(key = lambda x: x[1])


end = time.time()

print(lista)
total = (end - start)
print('Total time taken:',total)
Jainil Patel
  • 1,284
  • 7
  • 16
  • Wow that's really short, however I'm not quite sure what this line of code means/what it does. "lista.sort(key = lambda x: x[1])" – Ryan Johnson Jun 07 '19 at 07:55