I am trying to write a function namely fourslicebidirectionSearch() where I have to do as a title said. My problem is I can write each function on its own but I couldn't figure out how to apply bidirection to four sliced integers.
def BiDirectionSearch(key, ls):
i = 0 # to count a number loop
j = len(ls) - 1
while i < j:
if ls[i] == key or ls[j] == key:
return True, i + 1
i += 1
j -= 1
return False, i
def FourSliceSearch(key, ls):
n = int(len(ls) / 4)
s1 = ls[0:n]
s2 = ls[n:2 * n]
s3 = ls[2 * n:3 * n]
s4 = ls[3 * n:]
i1 = 0
i2 = 0
i3 = 0
i4 = 0
count = 0 # to count a number of loop
for i in range(len(s1)):
if s1[i1] == key or s2[i2] == key or s3[i3] == key or s4[i4] == key:
count += 1
return True, count
i1 += 1
i2 += 1
i3 += 1
i4 += 1
count += 1
return False, count
myNum2 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
key = 9
result, loopcount2 = BiDirectionSearch(key, myNum2)
result, loopcount3 = FourSliceSearch(key, myNum2)
if result:
print(f'{key} is found in {myNum2}')
print(f'For LienarSearch(), it takes {loopcount} loop(s) to find {key}.')
print(f'For BiDirectionSearch(), it takes {loopcount2} loop(s) to find {key}.')
print(f'For FourSliceSearch(), it takes {loopcount3} loop(s) to find {key}.')
else:
print(f'{key} is not in {myNum2} and it takes {loopcount} loop(s)')