best way to determine sequence ordering?

K

Kay Schluehr

* building a dict of indicies::
positions = dict((item, i) for i, item in enumerate(L))

if positions['A'] < positions['D']:
# do some stuff

You'll only get a gain from this version if you need to do several
comparisons instead of just one.

Hi Steven,

your solution may not create the correct answer if an item occurs twice
in the list because the later occurrence overwrites the former during
dict creation:
L = ['C', 'A', 'D', 'B', 'A']
dict((item, i) for i, item in enumerate(L))
{'A': 4, 'C': 0, 'B': 3, 'D': 2}

This gives the impression that 'D' always precedes 'A' which is wrong.
 
S

Steven Bethard

Kay said:
* building a dict of indicies::

positions = dict((item, i) for i, item in enumerate(L))

if positions['A'] < positions['D']:
# do some stuff

You'll only get a gain from this version if you need to do several
comparisons instead of just one.

Hi Steven,

your solution may not create the correct answer if an item occurs twice
in the list because the later occurrence overwrites the former during
dict creation:
L = ['C', 'A', 'D', 'B', 'A']
dict((item, i) for i, item in enumerate(L))
{'A': 4, 'C': 0, 'B': 3, 'D': 2}

This gives the impression that 'D' always precedes 'A' which is wrong.

Yeah, thanks for the update. I meant to include that too.

STeVe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,294
Messages
2,571,511
Members
48,200
Latest member
SCPKatheri

Latest Threads

Top