0

Why we use " len(list)-1 " instead of " len(list) " please help me , thank you

start = 0 def praneeth(list,start,end,key): while(start <= end): mid = start+end//2 if list[mid] == key: return mid elif list[mid] < key: start = mid+1 else: end = mid-1 return -1 list = [10,20,30,40,50,60,70,80,88,90,100] key = 20 kumar = praneeth(list,0,len(list)-1,key) if kumar != -1: print(kumar) else: print("Number not found")

3rd Jun 2021, 2:18 AM
Praneeth Kumar
Praneeth Kumar - avatar
8 Respostas
+ 1
because 'end' argument is supposed to be included, and indexes start at zero ^^
3rd Jun 2021, 2:24 AM
visph
visph - avatar
+ 1
Praneeth Kumar in range, end argument is not included ^^
3rd Jun 2021, 2:28 AM
visph
visph - avatar
+ 1
in your function you are testing if start<=end, so end is included... in range, end is not included ;)
3rd Jun 2021, 2:39 AM
visph
visph - avatar
+ 1
no: range(0,end) is same that range(end)
3rd Jun 2021, 2:41 AM
visph
visph - avatar
+ 1
range(3) is same as [0,1,2]
3rd Jun 2021, 2:42 AM
visph
visph - avatar
0
But in for loop we use for i in range(len(list)) Not using len(list)-1
3rd Jun 2021, 2:27 AM
Praneeth Kumar
Praneeth Kumar - avatar
0
for i in range(0,len(list)-1): And for i in range(len(list)): Both are same ????
3rd Jun 2021, 2:40 AM
Praneeth Kumar
Praneeth Kumar - avatar
0
yes, default start value is zero...
3rd Jun 2021, 2:40 AM
visph
visph - avatar