Order by pair comparisons: Difference between revisions
Content added Content deleted
(Promote to full task status) |
|||
Line 257: | Line 257: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Python: Binary insertion=== |
|||
Uses binary search to insert successive items into a growing ordered list. Comparisons are asked for. |
Uses binary search to insert successive items into a growing ordered list. Comparisons are asked for. |
||
Line 312: | Line 313: | ||
13: IS orange LESS-THAN red ? y/n: n |
13: IS orange LESS-THAN red ? y/n: n |
||
red orange yellow green blue indigo violet</pre> |
|||
===Python: Sort with custom comparator=== |
|||
This uses a custom comparator together with [https://docs.python.org/3/library/functools.html?highlight=cmp_to_key#functools.cmp_to_key functools.cmp_to_key] to sort the previous order in fourteen questions. |
|||
<lang python>from functools import cmp_to_key |
|||
def user_cmp(a, b): |
|||
return int(input(f"IS {a:>6} <, ==, or > {b:>6} answer -1, 0 or 1:")) |
|||
if __name__ == '__main__': |
|||
items = 'violet red green indigo blue yellow orange'.split() |
|||
ans = sorted(items, key=cmp_to_key(user_cmp)) |
|||
print('\n' + ' '.join(ans))</lang> |
|||
{{out}} |
|||
<pre>IS red <, ==, or > violet answer -1, 0 or 1:-1 |
|||
IS green <, ==, or > red answer -1, 0 or 1:1 |
|||
IS green <, ==, or > violet answer -1, 0 or 1:-1 |
|||
IS green <, ==, or > red answer -1, 0 or 1:1 |
|||
IS indigo <, ==, or > green answer -1, 0 or 1:1 |
|||
IS indigo <, ==, or > violet answer -1, 0 or 1:-1 |
|||
IS blue <, ==, or > indigo answer -1, 0 or 1:-1 |
|||
IS blue <, ==, or > green answer -1, 0 or 1:1 |
|||
IS yellow <, ==, or > blue answer -1, 0 or 1:-1 |
|||
IS yellow <, ==, or > green answer -1, 0 or 1:-1 |
|||
IS yellow <, ==, or > red answer -1, 0 or 1:1 |
|||
IS orange <, ==, or > blue answer -1, 0 or 1:-1 |
|||
IS orange <, ==, or > yellow answer -1, 0 or 1:-1 |
|||
IS orange <, ==, or > red answer -1, 0 or 1:1 |
|||
red orange yellow green blue indigo violet</pre> |
red orange yellow green blue indigo violet</pre> |