猜测算法似乎不起作用,通过Python猜测数字 [英] Guessing algorithm does not seem to work, guessing number by Python

查看:91
本文介绍了猜测算法似乎不起作用,通过Python猜测数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一些简单的算法,该算法应使python在尽可能少的猜测中猜测给定的数字。它似乎正在运行,但是非常慢。我究竟做错了什么。我已经阅读了几个有关此问题的主题,但找不到解决方案。我是新手程序员,所以欢迎您提出任何建议。

I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.

min = 1
max = 50

number = int(input(("please choose a number between 1 and 50: ")))

total = 0
guessed = 0

while guessed != 1:
    guess = int((min+max)/2)
    total += 1 

    if guess == number:
        print("The number has been found in ",total," guesses!")
        guessed = 1
    elif guess > number:
        min = guess + 1
    elif guess < number:
        max = guess - 1

谢谢

ps。我知道程序不会检查输入是否错误;)

ps. I am aware the program does not check for wrong input ;)

推荐答案

您的逻辑是倒退的。您想降低 max ,而又想提高 min 当您猜得太低时。尝试以下操作:

Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:

if guess == number:
    print("The number has been found in ",total," guesses!")
    guessed = 1
elif guess > number:
    max = guess - 1
elif guess < number:
    min = guess + 1

这篇关于猜测算法似乎不起作用,通过Python猜测数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆