Guest User

Untitled

a guest
Feb 18th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. # Interpolation search algorithm
  2. def interpolation_search(list, target_element, start, end):
  3.  
  4. if start <= end and (target_element >= list[start] and target_element <= list[end]):
  5. mid_point = start + int((float(end - start) / (list[end] - list[start])) * (target_element - list[start]))
  6.  
  7. if (list[mid_point] == target_element):
  8. return mid_point
  9. elif (list[mid_point] < target_element):
  10. return interpolation_search(list, target_element, mid_point + 1, end)
  11. else:
  12. return interpolation_search(list, target_element, start, mid_point - 1)
  13.  
  14. # Return -1 if condition is not fulfilled
  15. return -1
  16.  
  17. # A sample of sorted number list
  18. sorted_num_list = [1, 3, 10, 14, 18, 22, 49, 50, 66, 88, 120]
  19.  
  20. # Display the sorted number list
  21. print("List of numbers: {0}".format(sorted_num_list))
  22.  
  23. # Get user input
  24. while True:
  25. try:
  26. num = int(input("Enter a number to get the position: "))
  27. break
  28. except ValueError:
  29. print("Please enter a number only.\n")
  30.  
  31. # Performs interpolation search of
  32. # the number specified by the user.
  33. pos = interpolation_search(sorted_num_list, int(num), 0, len(sorted_num_list) - 1)
  34.  
  35. # Display the result
  36. print("The number {0} is found at position {1}.".format(num, pos) if pos != -1 else "The number you're looking for is not in the list.")
Add Comment
Please, Sign In to add comment