Write a function called NumDistinctDict that takes a single parameter alist that determines the number of distinct values in alist. For example, the list [1,2,4,2,7] contains 3 unique values (namely 1,2,4 and 7).

Recommended Answers

All 4 Replies

This sounds suspiciously like homework, so I'll just give you a hint.

someList.index(item) returns the index of the item if it's in some list. Otherwise, it'll throw ValueError.

Example:

listA = [1,2,3,5]
try:
	listA.index(4)
	print "Four is in the list."
except ValueError:
	print "Four isn't in the list."

This is very simple to do.

print len(set([1,2,4,2,7]))
Member Avatar for masterofpuppets

This is very simple to do.

print len(set([1,2,4,2,7]))

that's really useful...

you could also do it in the old fashion way

def NumDistinctDict( l ):
    distinct = []
    for num in l:
        if num not in distinct:
            distinct += [ num ]
    return len( distinct )

Let's hope it wasn't homework!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.