-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsets.py
51 lines (34 loc) · 1.3 KB
/
sets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/env python
'''
Example: The built-in set type
'''
import random
def randomWithReplacement(population, k):
'''Return k random elements of population with replacement.'''
nums = []
for x in range(k):
numList = random.sample(population, 1)
nums.append(numList[0])
return nums
if __name__ == '__main__':
# Get two lists of 50 random numbers from 0 - 49
nums1 = randomWithReplacement(range(50), 50)
nums2 = randomWithReplacement(range(50), 50)
# Get rid of the duplicates by putting them in sets.
uniqueNumsSet1 = set(nums1)
uniqueNumsSet2 = set(nums2)
# Put the sets back in lists so they can be sorted.
uniqueNumList1 = list(uniqueNumsSet1)
uniqueNumList1.sort()
uniqueNumList2 = list(uniqueNumsSet2)
uniqueNumList2.sort()
print('%d unique numbers in list 1.' % len(uniqueNumsSet1))
print('set 1: %s' % uniqueNumList1)
print('%d unique numbers in list 2.' % len(uniqueNumsSet2))
print('set 2: %s' % uniqueNumList2)
# Take the insection of the two sets
intersection = uniqueNumsSet1.intersection(uniqueNumsSet2)
intersectionList = list(intersection)
intersectionList.sort()
print('%d numbers common to both lists.' % len(intersection))
print('Numbers in common: %s' % intersectionList)