AI 猜数字 AI Studio

百度 AI Studio
学习打卡:自增 python里面没++、-- 可以 var_name += var_name

# 欧皇在线
import random
# 用户输入一个单位以内的数字,AI要用最少的次数猜中,并且显示出猜的次数和数字。
while True:
    y = int(input(" enter range: 0 ~ 1000 Please enter a number:"))
    if y in range(0, 1000):
        # 系统随机猜数
        x = int(random.randrange(0, 1000))
        temp1 = 0
        temp2 = 0
        error_count = 0
        while True:
            error_count += 1
            if y == x :
                break
            if y > x :
                temp1 = x
                x = random.randrange(temp1, 1000)
            if y < x :
                temp2 = x
                x = random.randrange(temp1, temp2)
        print("Guess the {} time. The number of you entered is {}".format(error_count, x))
    else:
        print('请输入一个0 ~ 1000范围内的数!')
        

也可以进行数据计算猜数(列如 average):
电脑来猜数字,它会猜中你输入的任何数在范围 ( 2 63 + 1 ) (-2^{63}+1) ( 2 63 1 ) (2^{63}-1) 内的数 :

# 欧皇在线
import random
x_max = random.randrange(0, (2**63-1))
x_min = random.randrange((-2**63+1), 0)
y = int(input("Please you enter a number:"))
print(x_max, x_min, y)
temp, count = 0, 0
while True:
    count += 1
    
    if y > x_max:
        x_min = x_max
        x_max = random.randrange(x_min, (2**63-1))
        print("1 x_max={} x_min={}".format(x_max, x_min)
    elif y < x_max:
        temp = x_min
        x_min = random.randrange(x_min, x_max)
        if y < x_min:
            count += 1
            x_max = x_min
            x_min = temp
            print("2.1 x_max={} x_min={}".format(x_max, x_min))
    print("2 x_max={} x_min={}".format(x_max, x_min))
    if y == x_max:
        print("The computer guessed {} times. The number is {}".format(count, x_max))
        break

现在不用欧皇的力量了:

x_max = 1000
print("Please enter a number. The number in 0 ~ {}".format(x_max))
y = int(input("enter:"))
x_min = 0
x_mid = 0
guess_time = 0
while True:
    if y == int(x_max) or y == int(x_min):
        print("Guess {} time! The number you put in is {} !".format(guess_time, (x_max if y == x_max else x_min)))
        break
    # 判断y在不在范围内
    if y in range(int(x_min), int(x_max)):
        guess_time += 1
    else:
        print("not within the scope of 0 ~ {} !".format(x_max))
        break
    # 计算y的值利用最大值和最小值的区间求均值,猜数!
    x_mid = int((x_min+x_max)/2)
    print("x_mid={}".format(x_mid))
    if y < x_max and y >= x_mid:
        x_min=x_mid
        print("x_min={}".format(x_min))
    if y > x_min and y <= x_mid:
        x_max=x_mid
        print("x_max={}".format(x_max))

发布了18 篇原创文章 · 获赞 3 · 访问量 1058

猜你喜欢

转载自blog.csdn.net/hjh_cos/article/details/103835490
AI
今日推荐