exercise11.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright (C) 2020, 2019 Girish M
  2. # This program is free software; you can redistribute it and/or modify
  3. # it under the terms of the GNU General Public License as published by
  4. # the Free Software Foundation; either version 3 of the License, or
  5. # (at your option) any later version.
  6. #
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU General Public License
  13. # along with this program; if not, write to the Free Software
  14. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  15. # MA 02110-1301, USA.
  16. #
  17. '''
  18. Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest) and another number.
  19. The function decides whether or not the given number is inside the list and returns (then prints) an appropriate boolean.
  20. Extras:
  21. Use binary search.
  22. '''
  23. # @author prince
  24. import math
  25. x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  26. n = int(input("enter a number, and we'll see if it's in the list: "))
  27. low = 0
  28. high = 9
  29. listLength = len(x)
  30. def binarysearch(n, x, low, high):
  31. mid = math.ceil((low + high)/2)
  32. if mid >= 0 and mid < listLength:
  33. if n == x[mid]:
  34. return True
  35. if n < x[mid]:
  36. high = mid -1
  37. if n > x[mid]:
  38. low = mid + 1
  39. return binarysearch(n, x, low, high)
  40. else:
  41. return False
  42. print(binarysearch(n, x, low, high))