Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Interpolation search algorithm
- def interpolation_search(list, target_element, start, end):
- if start <= end and (target_element >= list[start] and target_element <= list[end]):
- mid_point = start + int((float(end - start) / (list[end] - list[start])) * (target_element - list[start]))
- if (list[mid_point] == target_element):
- return mid_point
- elif (list[mid_point] < target_element):
- return interpolation_search(list, target_element, mid_point + 1, end)
- else:
- return interpolation_search(list, target_element, start, mid_point - 1)
- # Return -1 if condition is not fulfilled
- return -1
- # A sample of sorted number list
- sorted_num_list = [1, 3, 10, 14, 18, 22, 49, 50, 66, 88, 120]
- # Display the sorted number list
- print("List of numbers: {0}".format(sorted_num_list))
- # Get user input
- while True:
- try:
- num = int(input("Enter a number to get the position: "))
- break
- except ValueError:
- print("Please enter a number only.\n")
- # Performs interpolation search of
- # the number specified by the user.
- pos = interpolation_search(sorted_num_list, int(num), 0, len(sorted_num_list) - 1)
- # Display the result
- 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