|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +''' |
| 5 | +Take two lists, say for example these two: |
| 6 | +
|
| 7 | +a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 8 | +b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] |
| 9 | +and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes. |
| 10 | +
|
| 11 | +Extras: |
| 12 | +
|
| 13 | +- Randomly generate two lists to test this |
| 14 | +- Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon) |
| 15 | +''' |
| 16 | + |
| 17 | +import random |
| 18 | + |
| 19 | +a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 20 | +b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] |
| 21 | + |
| 22 | +###################################### |
| 23 | +# Randomly generate lists a and b |
| 24 | +###################################### |
| 25 | +length1 = random.randint(10,20) |
| 26 | +a = [random.randint(1,50) for i in range(length1)] |
| 27 | + |
| 28 | +length2 = random.randint(10,20) |
| 29 | +b = [random.randint(1,50) for i in range(length2)] |
| 30 | + |
| 31 | +print('list a: ', a) |
| 32 | +print('list b: ', b) |
| 33 | + |
| 34 | +####################################### |
| 35 | +# Calculate intersection of a and b |
| 36 | +####################################### |
| 37 | + |
| 38 | +# method 1: |
| 39 | +res = [] |
| 40 | +for i in a: |
| 41 | + if i in b: |
| 42 | + res.append(i) |
| 43 | + |
| 44 | +# Remove duplacates |
| 45 | +res = list(set(res)) |
| 46 | + |
| 47 | +print('Method 1:') |
| 48 | +print('The intersection of a&b is: ', res) |
| 49 | + |
| 50 | +# method 2: |
| 51 | +res = filter(lambda x:x in b, a) |
| 52 | +res = list(set(res)) |
| 53 | +print('Method 2:') |
| 54 | +print('The intersection of a&b is: ', res) |
| 55 | + |
| 56 | +# method 3: |
| 57 | +res = list(set(a) & set(b)) |
| 58 | +print('Method 3:') |
| 59 | +print('The intersection of a&b is: ', res) |
| 60 | + |
0 commit comments