fork download
  1. # lec10prob2.py
  2.  
  3. # In lecture, we saw a version of linear search that used the fact that a set
  4. # of elements is sorted in increasing order. Here is the code from lecture:
  5.  
  6. def search(L, e):
  7. for i in range(len(L)):
  8. if L[i] == e:
  9. return True
  10. if L[i] > e:
  11. return False
  12. return False
  13.  
  14. # Consider the following code, which is an alternative version of search.
  15.  
  16. def search1(L, e):
  17. for i in L:
  18. if i == e:
  19. return True
  20. if i > e:
  21. return False
  22. return False
  23.  
  24. # Which of the following statements is correct? You may assume that each
  25. # function is tested with a list L whose elements are sorted in increasing
  26. # order; for simplicity, assume L is a list of positive integers.
  27. #
  28. # - search and search1 return the same answers
  29. # - search and search1 return the same answers provided L is non-empty
  30. # - search and search1 return the same answers provided L is non-empty and e is in L
  31. # - search and search1 do not return the same answers
  32. # - search and search1 return the same answers for lists of length 0 and 1 only
  33.  
  34. # Sample list and calls to both search and search1 with different lists
  35. # to match conditions in above possible answers
  36.  
  37. # Search for a number in list
  38. print(search([2, 5, 7, 10, 15, 27, 35, 44], 35))
  39. print(search1([2, 5, 7, 10, 15, 27, 35, 44], 35))
  40. print
  41.  
  42. # Search for a number not in list
  43. print(search([2, 5, 7, 10, 15, 27, 35, 44], 3))
  44. print(search1([2, 5, 7, 10, 15, 27, 35, 44], 3))
  45. print
  46.  
  47. # Search for a number in an empty list
  48. print(search([], 5))
  49. print(search1([], 5))
  50. print
  51.  
  52. # Search for a number in a single element list
  53. print(search([5], 5))
  54. print(search1([5], 5))
  55. print
Success #stdin #stdout 0.01s 7096KB
stdin
Standard input is empty
stdout
True
True

False
False

False
False

True
True