0

I have a list of line segments on a plane (It's a class with 2 instances for the initial and final vertex). In my code, I detect which segments intersect with a previously inserted line and all those segments are then inserted into a list.

The segment class also has a function that can return a number based on it's position compared to other segment (the value itself doesn't matter, only the sign), which tells me if this segment being compared is to the left or to the right of the other segment.

I'd like to know if it is possible to sort a list using that kind of comparison function, since, so far, I've been able to find only sorting based on functions that return "meaningful" numbers (e.g., x is less than y, so x comes first)

Simply put, I have some line segments in a list, and I'd like to sort them out with a function that only tells me if a certain segment, say, S1 is to the right or to the left of another segment S2 and nothing else.

Taku
  • 31,927
  • 11
  • 74
  • 85
htcoelho
  • 65
  • 7
  • How do you sort `[S1, S2, S3]` list if `S1` can't be compared with `S3`? – jfs Oct 27 '14 at 08:42
  • It's not that it can't be compared, but the comparison I'm trying to do will only look at the neighbours to give a result. It's like Bubble sort, I guess. For example, thinking as numbers, I'd be able to know if an element is greater than it's neighbours, but not how bigger it is. – htcoelho Oct 27 '14 at 08:59
  • s3 is not s1's neighbor i.e., they are not comparable. – jfs Oct 27 '14 at 09:02
  • Oh, I think I understood what you meant. So if I wanted to achieve that kind of sorting, I'd have to make a new function instead of using list.sort() or sorted()? – htcoelho Oct 27 '14 at 09:06
  • If you can compare arbitrary line segments then define cmp_line_segment() function (return -1 if less, 0 if equal, +1 if greater) and pass it to functools.cmp_to_key() function, to get `key` function that you can pass to `sorted()` builtin. – jfs Oct 27 '14 at 09:08
  • I understand. Thank you very much for your patience. If you'd like, just make that an answer and I'll accept it :) – htcoelho Oct 27 '14 at 09:12

1 Answers1

0

Use custom sort with 'key' option, I think it will help: https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions or Custom sort python

Community
  • 1
  • 1
The Godfather
  • 4,235
  • 4
  • 39
  • 61