循环在第几圈停下

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

(每道题开头都有同一段游戏核心:new_round 开一局、parse 校验输入、judge 比大小、step 记一次猜测、score 算分。秘密固定是 73。)

输入列表里有 7 行,但第 6 行就猜中了。看循环停在哪、还剩几行没读:

LIMIT = 7

def new_round(secret):
    return {"secret": secret, "tries": 0, "low": 1, "high": 100, "over": False, "won": False}

def parse(line):
    s = line.strip()
    if s in ("q", "r"):
        return s
    if not s.isdigit():
        return None
    n = int(s)
    if n < 1 or n > 100:
        return None
    return n

def judge(secret, n):
    if n > secret:
        return "大了"
    if n < secret:
        return "小了"
    return "对了"

def step(st, n):
    st["tries"] += 1
    r = judge(st["secret"], n)
    if r == "大了" and n - 1 < st["high"]:
        st["high"] = n - 1
    if r == "小了" and n + 1 > st["low"]:
        st["low"] = n + 1
    if r == "对了":
        st["won"] = True
    if st["won"] or st["tries"] >= LIMIT:
        st["over"] = True
    return r

def score(st):
    return LIMIT + 1 - st["tries"] if st["won"] else 0

LINES = ["50", "75", "62", "68", "71", "73", "10"]
st = new_round(73)
i = 0
last = ""
while not st["over"]:
    last = step(st, parse(LINES[i]))
    i += 1
print(str(st["tries"]) + "/" + last + "/" + str(len(LINES) - i))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论