码迷,mamicode.com
首页 > 编程语言 > 详细

python猜数脚本(电脑猜测)(二分法)

时间:2016-12-14 19:18:57      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:设置   round   output   stream   结束   pre   数组   stdout   end   

# 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猜数脚本(电脑猜测)(二分法)

标签:设置   round   output   stream   结束   pre   数组   stdout   end   

原文地址:http://www.cnblogs.com/castlevania/p/6180253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!