[Tutor] Testing if a number occurs more than once

Michael Williams michael.williams@st-annes.oxford.ac.uk
Mon Dec 2 12:49:02 2002


Hi,

I think I may be missing out on something really obvious here (such as 
a built-in), but I'm trying to ascertain whether a given number occurs 
more than once in a list. My current solution involves generating a 
dictionary of the frequency with which each number occurs and then 
checking if the size of that dictionary is the same as the size of the 
original list (if it is then each number occurs once). This strikes me 
as not only convoluted, but slow (this is the dominant loop of the 
program). There must be a better way! Any suggestions?

My current solution follows:

def freqs(L):
     # dictionary of frequencies of the elements of list L
     res = {}
     for x in L:
         res[x]= res.get(x,0)+1
     return res

def morethanone(L):
     if len(freqs(L)) == len(L):
       return 0
     else:
       return 1

 >>> l1 = [5,6,7]
 >>> morethanone(l1)
0
 >>> l2 = [5,6,6]
 >>> morethanone(l2)
1

-- 
Michael