当前位置:   article > 正文

关于TypeError: list indices must be integers or slices, not float报错

list indices must be integers or slices, not float
  1. def binary_search(list,item):
  2. low = 0
  3. high = len(list) - 1
  4. while low <= high:
  5. mid=(low+high)/2
  6. guess=list[mid]
  7. if guess == item:
  8. return mid
  9. if guess > item:
  10. high = mid - 1
  11. else:
  12. low = mid + 1
  13. return None
  14. my_list=[1,3,5,7,9]
  15. print(binary_search(my_list,3))

经查阅得到“/”是浮点数除法,但是在此程序中需要整除,所以要用“%”或者“//”

  1. def binary_search(list,item):
  2. low = 0
  3. high = len(list) - 1
  4. while low <= high:
  5. mid=(low+high)%2#这里报错错了,
  6. guess=list[mid]
  7. if guess == item:
  8. return mid
  9. if guess > item:
  10. high = mid - 1
  11. else:
  12. low = mid + 1
  13. return None
  14. my_list=[1,3,5,7,9]
  15. print(binary_search(my_list,3))

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/642890
推荐阅读
相关标签
  

闽ICP备14008679号