• Python模拟人猜数过程(折半查找)


    import random
    # (0,1000)随机产生一个数
    key = random.randint(1,1000)
    # 用来统计猜的次数
    count = 0

    # 定义一个折半查找的函数
    def BinSearch(array, key, low, high):
    global count
    mid = int((low+high)/2)
    if key == array[mid]: # 若找到
    count += 1
    print("您总共猜了次数是:%d"%count)
    print("恭喜您猜对了,答案是:" )
    return array[mid]
    if low > high:
    return False

    if key < array[mid]:
    print("小于猜的数")
    count += 1
    return BinSearch(array, key, low, mid-1) #递归
    if key > array[mid]:
    count += 1
    print("大于猜的数")
    return BinSearch(array, key, mid+1, high)



    if __name__ == "__main__":
    # 给定一个列表
    num_value_list = list(range(1, 1001))
    # 通过折半查找,找到随机的数
    ret = BinSearch(num_value_list, key, 0, len(num_value_list)-1)
    print(ret)
  • 相关阅读:
    springcloud-EurekaServer模块
    springcloud-消费者订单模块
    springboot配置热部署
    swagger依赖和配置类
    springcloud-支付模块构建
    jQuery基础
    JavaScript之实例
    JavaScript之DOM
    JavaScript之BOM
    JavaScript函数与对象
  • 原文地址:https://www.cnblogs.com/yunlongaimeng/p/8835109.html
Copyright © 2020-2023  润新知