Better way to do this dict comprehesion

MRAB python at mrabarnett.plus.com
Tue Mar 7 21:55:14 EST 2017


On 2017-03-08 02:37, Chris Angelico wrote:
> On Wed, Mar 8, 2017 at 1:28 PM, Sayth Renshaw <flebber.crue at gmail.com> wrote:
>> I have got this dictionary comprehension and it works but how can I do it better?
>>
>> from collections import Counter
>>
>> def find_it(seq):
>>      counts = dict(Counter(seq))
>>      a = [(k, v) for k,v in counts.items() if v % 3 == 0]
>>      return a[0][0]
>>
>> test_seq = [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]
>>
>> so this returns 5 which is great and the point of the problem I was doing.
>>
>> Can also do it like this
>> def find_it(seq):
>>      counts = dict(Counter(seq))
>>      a = [(k) for k,v in counts.items() if v % 3 == 0]
>>      return a[0]
>>
>> But the given problem states there will always only be one number appearing an odd number of times given that is there a neater way to get the answer?
>
> Take a step back for a moment. Are you trying to find something that
> appears an odd number of times, or a number of times that counts by
> three? First figure that out, THEN see if there's a better way to do
> what you're doing.
>
> To find an unpaired number in linear time with minimal space, try
> stepping through the list and either adding to a set or removing from
> it. At the end, your set should contain exactly one element. I'll let
> you write the actual code :)
>
Using Counter seems like a simpler way to me. I wouldn't bother about 
other ways unless that way wasn't "good enough" for some reason.




More information about the Python-list mailing list