Better way to do this dict comprehesion

Robert L. No_spamming at noWhere_7073.org
Sat Apr 1 04:13:34 EDT 2017


On 3/7/2017, Sayth Renshaw 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?


[20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5].group_by{|x| x}.
find{|k,v| v.size.odd?}.first

 ===>
5

-- 
sig redacted


More information about the Python-list mailing list