Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96174
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
15
def has_duplicates(t):
16
"""Checks whether any element appears more than once in a sequence.
17
18
Simple version using a for loop.
19
20
t: sequence
21
"""
22
d = {}
23
for x in t:
24
if x in d:
25
return True
26
d[x] = True
27
return False
28
29
30
def has_duplicates2(t):
31
"""Checks whether any element appears more than once in a sequence.
32
33
Faster version using a set.
34
35
t: sequence
36
"""
37
return len(set(t)) < len(t)
38
39
40
if __name__ == '__main__':
41
t = [1, 2, 3]
42
print(has_duplicates(t))
43
t.append(1)
44
print(has_duplicates(t))
45
46
t = [1, 2, 3]
47
print(has_duplicates2(t))
48
t.append(1)
49
print(has_duplicates2(t))
50
51
52