[Tutor] Testing if a number occurs more than once

Alfred Milgrom fredm@smartypantsco.com
Tue Dec 3 02:46:00 2002


Hi Michael:

What about something like:

def morethanone(list):
     for i in range(len(list)):
         if list[i] in list[i+1:]:
             return 1
     return 0

list = [your list]
print morethanone(list)

This goes through each element in the list, and checks if that element 
exists in the rest of the list. (You don't have to check earlier in the 
list, because you already know that doesn't have any doubles).

HTH,
Fred Milgrom


At 05:48 PM 2/12/02 +0000, you wrote:
>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?