I'm trying to find the index of a number in an array(list) but sometimes it falls into the if statement (if upper < lower) even though it's not a true statement.
def recurse(lower,upper,result,target):
if upper < lower:
print("Error, Upper is less then Lower")
return -999
midpoint = (lower + upper)//2
guess = result[midpoint]
if guess == target:
return midpoint
else:
if guess > target:
upper = midpoint -1
return recurse(lower,upper,result,target)
else:
lower = midpoint +1
return recurse(lower,upper,result,target)
result5= recurse(0,30,result,215)
print("The index of that number is : ",result5)
I have formed a random generation array and have 30 numbers generated between 201 and 300
def randomList(array):
array = []
for x in range(29):
r = random.randint(201,300)
array.append(r)
return array
result = randomList(result)
print("Random list of 30 numbers between 201-300",result)
I have pasted the list result [282, 215, 204, 295, 236, 232, 229, 218, 295, 214, 287, 295, 270, 212, 276, 255, 205, 204, 212, 228, 230, 265, 278, 204, 272, 226, 292, 284, 290]
My goal for the recuse function is to display the index of the number I send in the target parameter. Sometimes it actually works and will tell me the index number, but sometimes it doesn't. I'm pretty stumped. I'm sorry for formatting errors.
The result from sending the target number 215 is: The index of that number is : 1 Which is completely acurate and works, but the problem arises when I find another number, lets say 282, it should give me 0. But it gives me my return value of -999. Or when I do 272, same problem, return -999. It only works on some values. Anyways I'd appreciate any light that can be shed on this problem. Thank you.
Aucun commentaire:
Enregistrer un commentaire