Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何编写在python中使用的代码?_Python 3.x - Fatal编程技术网

Python 3.x 如何编写在python中使用的代码?

Python 3.x 如何编写在python中使用的代码?,python-3.x,Python 3.x,我们的教科书中有这个例子。然而,这个例子是用Java编写的(我想,我不熟悉Java),我们的任务是用python编写的。有没有办法把这个例子翻译成python BinarySearch(numbers, numbersSize, key) { mid = 0 low = 0 high = numbersSize - 1 while (high >= low) { mid = (high + low) / 2 if (numbers[mid]

我们的教科书中有这个例子。然而,这个例子是用Java编写的(我想,我不熟悉Java),我们的任务是用python编写的。有没有办法把这个例子翻译成python

BinarySearch(numbers, numbersSize, key) {
   mid = 0
   low = 0
   high = numbersSize - 1

   while (high >= low) {
      mid = (high + low) / 2
      if (numbers[mid] < key) {
         low = mid + 1
      }
      else if (numbers[mid] > key) {
         high = mid - 1
      }
      else {
         return mid
      }
   }

   return -1 // not found
}
main() {
   numbers = { 2, 4, 7, 10, 11, 32, 45, 87 }
   NUMBERS_SIZE = 8
   i = 0
   key = 0
   keyIndex = 0

   print("NUMBERS: ")
   for (i = 0; i < NUMBERS_SIZE; ++i) {
      print(numbers[i] + " ")
   }
   printLine()

   print("Enter a value: ")
   key = getIntFromUser()

   keyIndex = BinarySearch(numbers, NUMBERS_SIZE, key)

   if (keyIndex == -1) {
      printLine(key + " was not found.")
   }
   else {
      printLine("Found " + key + " at index " + keyIndex + ".")
   }
}
BinarySearch(数字、数字大小、键){
mid=0
低=0
高=数字大小-1
而(高>=低){
中=(高+低)/2
如果(数字[中间]<键){
低=中+1
}
else if(数字[mid]>键){
高=中-1
}
否则{
中途返回
}
}
返回-1//未找到
}
main(){
数字={2,4,7,10,11,32,45,87}
数字大小=8
i=0
键=0
keyIndex=0
打印(“数字:”)
对于(i=0;i
它不是Java语言

这是Py代码

def binary_search(item_list,item):
    first = 0
    last = len(item_list)-1
    found = False
    while(first<=last and not found):
        mid = (first + last)//2
        if item_list[mid] == item :
            found = True
        else:
            if item < item_list[mid]:
                last = mid - 1
            else:
                first = mid + 1 
    return found

print(binary_search([1,2,3,5,8], 6))
print(binary_search([1,2,3,5,8], 5))
def二进制搜索(项目列表,项目):
第一个=0
last=len(项目列表)-1
发现=错误
而