Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total Order in Python

What would be an elegant way to represent an arbitrary total order between elements of a list in Python, e.g. the function torder in the following example (where C>B>A). Edit: I assume the list defines the order:

>>> s = ['A','B','C']
>>> torder('B')
['A']
>>> torder('C')
['A','B']

I could do that using if and elif if the list is short but was looking for something more pythonic.

like image 215
Vladtn Avatar asked Jul 12 '26 03:07

Vladtn


2 Answers

def orde(i, s):
    t = sorted(s)
    return t[:t.index(i)]

s = ['A','B','C']
orde("B", s)
import itertools
itertools.takewhile(lambda x: x != 'C', s)

If order is not defined by the position in the list:

sorted(filter(lambda x: x < 'C', s))
like image 30
Karoly Horvath Avatar answered Jul 14 '26 16:07

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!