Issue
I would like to group together different search algorithms in a single loop. However, I don’t know how to include algorithms with different number of parameters. Loop is this:
search_algorithms = [linearSearch, jumpSearch, exponentialSearch]
for i in range(len(search_algorithms)):
start = default_timer()
result = search_algorithms[i](arr, len(arr), target)
end = default_timer()
time = timedelta(seconds=end-start)
print("{}".format(search_algorithms[i].__name__))
print("Target element is present at index", result)
print("Searching executed in {} seconds \n".format(time))
Is there some simple way how to include for instance binary search defined as def binarySearch(arr, l, r, x):
? Thanks a lot.
Solution
You can store the list of tuples in search_algorithms
where the first element is a function, and the second one is a list of arguments.
search_algorithms = [
(linearSearch, [arg1, arg2]),
(jumpSearch, [arg1]),
(exponentialSearch, [arg1, arg2, arg3]),
]
for fn, args in search_algorithms:
fn(*args)
Answered By – Marian Szenfeld
Answer Checked By – Terry (BugsFixing Volunteer)