For those who scratched their heads during the J part of Dr. Bate's
talk, what follows is four ways in python to tackle that same problem,
checking if a list contains duplicate items.
Two of the approaches are similar in spirit to his J solution code. Some
may also feel the connection here to Jay Smith's Clojure talk with my
direct use of map and filter. Also worth seeing how the same concepts
are embodied by of python generator expressions. (lazy version of list
comprehensions)
#!/usr/bin/env python
EXAMPLE_DATA = (
(1, 5, 7, 4, 5, 9), # test case 1, duplicates(ls) == True
(1, 3, 7, 4, 5, 9), # test case 2, duplicates(ls) == False
(5, 5, 7, 4, 5, 9), # test case 3, duplicates(ls) == True
)
def test_examples():
for test in EXAMPLE_DATA:
print duplicates(test), test
print
# one procedural approach
def duplicates(ls):
for i in ls:
count = 0
for j in ls:
if i == j:
count+=1
if count > 1:
return True
return False
test_examples()
# A lisp-like approach similar to Dr. Bate's J code
def count(n, ls):
return sum( map( lambda y: 1,
filter(lambda x: x==n,
ls ) )
)
def duplicates(ls):
return any( map( lambda y: count(y, ls) > 1,
ls )
)
test_examples()
# A python approach that's closer to Dr. Bate J code
def count(n, ls):
return sum( 1
for x in ls
if x == n )
def duplicates(ls):
return any( count(y, ls) > 1 for y in ls )
test_examples()
# Mark's approach
def duplicates(ls):
return len(ls) != len(set(ls))
test_examples()
_______________________________________________
SkullSpace Discuss Mailing List
Help: http://www.skullspace.ca/wiki/index.php/Mailing_List#Discuss
Archive: https://groups.google.com/group/skullspace-discuss-archive/