题目
猜数字互动游戏:程序内置随机目标数,用户多轮输入猜测值,程序根据偏大或偏小给出提示,直至猜中并输出总猜测轮数。
输入格式:多行输入猜测的整数数值,直到猜中。
输出格式:偏大输出 high,偏小输出 low,猜中输出 ok 尝试次数。
数据范围与约定:秘密目标数在 1~100 之间。
思路与算法
1. 循环交互结构
使用 while True: 驱动交互,维护累加猜测次数 tries += 1。
2. 二分逼近
每次根据 high 或 low 折半搜索,可以在最少轮次内命中目标。
完整程序
import random
import sys
# 固定随机种子确保评测一致性
random.seed(42)
secret = random.randint(1, 100)
tries = 0
inputs = sys.stdin.read().split()
for token in inputs:
guess = int(token)
tries += 1
if guess > secret:
print('high')
elif guess < secret:
print('low')
else:
print(f'ok {tries}')
break运行示例
输入:
50
75
88
82输出:
low
low
high
ok 4其它写法
下面每种写法都是完整程序,输入输出格式与正文一致,便于对照。
二分猜数
secret 固定为 82(与 random.seed(42) 时 randint 一致),按 high/low 收缩区间。
程序:
#!/usr/bin/python3
# coding=utf-8
secret = 82
lo, hi = 1, 100
tries = 0
while True:
guess = int(input())
tries += 1
if guess > secret:
print("high")
hi = guess - 1
elif guess < secret:
print("low")
lo = guess + 1
else:
print(f"ok {tries}")
break
if lo > hi:
break输入:
50
75
88
82输出:
low
low
high
ok 4