newbie:unique problem

Brian van den Broek bvande at po-box.mcgill.ca
Fri Mar 18 16:38:40 CET 2005


Heiko Wundram said unto the world upon 2005-03-18 01:27:
> On Thursday 17 March 2005 23:31, Brian van den Broek wrote:
> 
>>Am I not
>>right in thinking that with the dict approach there is no guarantee
>>that the order from the original list will be preserved?
> 
> 
> Yup, absolutely right that the original ordering will not be preserved. But, I 
> wonder whether this actually matters, when the op is actually using these 
> strings as a sort of set (to check whether someone belongs to some group, if 
> I understand him correctly).


Thanks for confirming that, Heiko. (My understanding of programming 
and Python is still shaky in quite a few places :-)


>>Also, Heiko, I wonder what is the reason for reversed(oldlist)? Since
>>the list isn't being mutated, there isn't any danger in forward
>>iteration over it. (Plus, unless I'm mistaken, its the only thing
>>making yours a 2.4-only solution.)
> 
> 
> The reason for walking the list backwards is easily demonstrated by the 
> following two runs:

<SNIP two functions, one with and one without the use of reversed>


>>>>uniqueItems(["AAA BC","BBB KK","CCC TD","AAA KP","CCC TD"])
> 
> ['AAA BC', 'BBB KK', 'CCC TD']
> 
>>>>uniqueItemsWithoutRev(["AAA BC","BBB KK","CCC TD","AAA KP","CCC TD"])
> 
> ['AAA KP', 'BBB KK', 'CCC TD']
> 
> When you walk the list forwards, the item that gets returned for the 
> corresponding "key" is the item that is last found (as I don't check whether 
> the item is already in the dict in the loop, but always just set), when you 
> walk the list backwards, the item that is last found backwards (thus farthest 
> in front) is returned.
> 
> In case this doesn't matter (well, I guess it actually doesn't, as the OP only 
> needs the first n chars, that's the reason for this function), you can easily 
> leave out the reversed() and remove the constraint on Python 2.4. If you must 
> have it in this order, and still use Python <2.4, you'd need to use something 
> like oldlist[::-1], which will copy the list. reversed(list) does an 
> optimization.


This seems a bit funny to me. My version took a speed hit as I was 
concerned to preserve order, whereas yours uses reversed because you 
cared about how the canonical representative were selected. But 
neither of our concerns were really in the OP's problem spec. :-)

Since I didn't share your concern about the selection of canonical 
representatives, the reversed puzzled me. Thanks for posting your 
rationale for its use.

Best,

Brian vdB




More information about the Python-list mailing list