首页 > 代码库 > python猜数脚本(电脑猜测)(二分法)
python猜数脚本(电脑猜测)(二分法)
# coding=utf-8
# 猜数
# 记录猜数的过程
import random
com_result=[] #存放电脑结果,数组
com_count=0 #存放电脑猜测次数
ran=random.randint(0,100) #随机生成数字
print(‘Start Guessing 开始猜测‘)
up=100 #设置上限和下限
down=0
print(‘Human provide random number is: ‘,ran) #人随机提供一个数
guessing=0 #为循环初始化
while (guessing<=0):
com_number=round((down+up)/2) #设置每次循环,电脑猜测的随机数
if com_number<ran:
down=com_number #猜小了,把下限提高
com_result.append(com_number) #把猜测的数字存入数组
com_count+=1 #猜测次数+1
print(com_number,‘ is smaller than‘ ,ran) #显示猜测数字
if com_number>ran:
up=com_number
com_result.append(com_number)
com_count+=1
print(com_number,‘ is bigger than‘,ran)
if com_number==ran:
com_result.append(com_number)
com_count+=1
print(‘Finally‘)
print(‘Computer\‘s guessing list: ‘,com_result)
print(‘Computer have tried: ‘,com_count)
guessing=1 #结束猜测
Start Guessing Human provide random number is: 67 50 is smaller than 67 75 is bigger than 67 62 is smaller than 67 68 is bigger than 67 65 is smaller than 67 66 is smaller than 67 Finally Computer‘s guessing list: [50, 75, 62, 68, 65, 66, 67] Computer have tried: 7
python猜数脚本(电脑猜测)(二分法)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。