Guest User

Untitled

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