fork download
  1. # -*- coding: cp1252 -*-
  2. # list_intersection.py
  3. # MIT OCW 6.189 Homework 3
  4. # Exercise 3.1 – Additional List Practice
  5. # Mechanical MOOC
  6. # Written for Python 3
  7. # Judy Young
  8. # July 23, 2013
  9. # Return a list that gives the intersection of the two lists
  10. # ie, a list of elements that are common to both lists.
  11.  
  12. def list_intersection(list_1, list_2):
  13. new_list = []
  14. for item in list_1:
  15. if item in list_2:
  16. new_list.append(item)
  17. return new_list
  18.  
  19. print list_intersection([1, 3, 5], [5, 3, 1])
  20. print list_intersection([1, 3, 6, 9], [10, 14, 3, 72, 9])
  21. print list_intersection([2, 3], [3, 3, 3, 2, 10])
  22. print list_intersection([2, 4, 6], [1, 3, 5])
  23. print list_intersection([1, 1, 2, 3, 5, 8, 13], [1, 3, 5, 7, 9, 11, 13])
  24. print list_intersection([1, 3, 5, 7, 9, 11, 13], [1, 1, 2, 3, 5, 8, 13])
  25.  
Success #stdin #stdout 0.01s 7768KB
stdin
Standard input is empty
stdout
[1, 3, 5]
[3, 9]
[2, 3]
[]
[1, 1, 3, 5, 13]
[1, 3, 5, 13]