将游戏伪代码转化为python
让计算机猜测用户在 1 到 1000 之间选择的数字,猜测次数不超过 10 次。此作业使用一种称为二分搜索的算法。 每次猜测后,算法都会将搜索的可能答案数量减少一半。 完整的伪代码 程序如下; 你的任务是把它变成一个可以工作的Python程序。 程序应该首先在屏幕上打印指令,解释用户 应选择 1 到 1000 之间的数字,计算机将在不超过 10 次尝试。 然后它开始进行猜测,每次猜测后它都会要求用户提供反馈。 如果猜测需要更低,则应指示用户输入 -1,如果正确则输入 0, 如果需要更高,则为 1。当程序猜测正确时,它应该报告需要猜测多少次。 如果用户输入无效响应,则应重复说明并允许用户重试。
伪代码
- Print instructions to the user
-Start with high = 1000, low = 1, and tries = 1
- While high is greater than low
- Guess the average of high and low
- Ask the user to respond to the guess
- Handle the four possible outcomes:
- If the guess was right, print a message that tries guesses were required and quit the program
- If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries
- If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries
- If the user entered an incorrect value, print out the instructions again
- high and low must be equal, so print out the answer and the value of tries
我需要一些认真的帮助! 我根本不明白这些东西! 这就是我所拥有的一切
def main(x, nums, low, high):
input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ")
for i in range (1, 1001):
main()
,我什至不知道这是否正确!
Make the computer guess a number that the user chooses between 1 and 1000 in no more than 10 guesses.This assignment uses an algorithm called a binary search. After each guess, the algorithm cuts the number of possible answers to search in half. Pseudocode for the complete
program is given below; your task is to turn it into a working python program.
The program should start by printing instructions to the screen, explaining that the user
should pick a number between 1 and 1000 and the computer will guess it in no more than
10 tries. It then starts making guesses, and after each guess it asks the user for feedback.
The user should be instructed to enter -1 if the guess needs to be lower, 0 if it was right,
and 1 if it needs to be higher.When the program guesses correctly, it should report how many guesses were required. If the user enters an invalid response, the instructions should be repeated and the user allowed to try again.
Pseudocode
- Print instructions to the user
-Start with high = 1000, low = 1, and tries = 1
- While high is greater than low
- Guess the average of high and low
- Ask the user to respond to the guess
- Handle the four possible outcomes:
- If the guess was right, print a message that tries guesses were required and quit the program
- If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries
- If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries
- If the user entered an incorrect value, print out the instructions again
- high and low must be equal, so print out the answer and the value of tries
I need some serious help! I don't understand any of this stuff at all!
This is all I have
def main(x, nums, low, high):
input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ")
for i in range (1, 1001):
main()
and I don't even know if it's right!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您显然对编程非常陌生,我想这就是社区延迟响应的原因之一。 很难决定从哪里开始以及如何指导您完成整个练习。
因此,在您在这里得到一个好的答案之前,包括让您了解那里发生的情况,并指导您自己构建解决方案(理想情况下!),我建议您访问此页面以尝试了解实际问题本身。
http://www.openbookproject.net/pybiblio/gasp/course/ 4-highlow.html
同时,查看此线程中的所有答案并继续编辑您的帖子,以便我们知道您已经明白了。
You're obviously very new to programming, and I guess that is one of the reasons for a delayed response from the community. It's tough to decide where to start and how to guide you through this whole exercise.
So, before you get a good answer here that includes making you understand what's happening there, and guiding you through building the solution yourself (ideally!) I would suggest you visit this page to try to get a grasp of the actual problem itself.
http://www.openbookproject.net/pybiblio/gasp/course/4-highlow.html
In the meantime, look at all the answers in this thread and keep editing your post so that we know you're getting it.
与伪代码不完全匹配,但它可以工作。 哈哈;)
我知道这是一篇邪恶的旧帖子,但这也是我得到的同样的作业。 这是我最终得到的结果:
Doesn't match the psudocode exactly but it works. lol ;)
I know this is a wicked old post but this is the same assignment I got also. Here is what I ended up with:
好吧,使用 Python 的好处是它几乎是伪代码。
现在,让我们考虑一下各个步骤:
如何获得高点和低点之间的平均值?
如何询问用户回答者是否正确
Python 中的“if”语句是什么样的,以及如何编写伪代码输出为 if 语句?
这是另一个提示——您可以将 python 作为解释器运行并尝试各个语句,因此,例如,您可以
计算您认为应该是它们之间的平均值或中点(提示:15)
Okay, the nice part about using Python is that it's almost pseudocode anyway.
Now, let's think about the individual steps:
How do you get the average between high and low?
How do you ask the user if the answerr is correct
What do "if" statements look like in Python, and how would you write the pseudocode out as if statements?
Here's another hint -- you can run python as an interpreter and try individual statements along, so, for example, you could do
then compute what you think should be the average or midpoint between them (hint: 15)
欢迎来到堆栈溢出!
这里的技巧是要意识到你的 Python 程序应该看起来几乎像伪代码。
首先,让我们尝试准确理解伪代码正在做什么。 如果我们必须与伪代码描述的程序进行交互,它看起来会像这样:
等等。
当我们第一次想到我们的数字时,程序只知道它在 1 到 1000 之间。它通过设置变量来表示这个知识'low' 为 1,变量 'high' 为 1000。它的第一个猜测是这些数字的平均值,即 500。
当我们告诉程序我们的数字大于 500 后,它会将 'low' 的值更新为501。换句话说,程序知道我们的数字在 501 和 1000 之间。然后它猜测 501 和 1000 的平均值,即 750。我们告诉它我们的数字较低,因此程序更新 'high 的值' 到 749,然后猜测 501 和 749 的平均值,依此类推,直到猜对,或者将可能的范围缩小到一个数字(意味着它的下一个猜测将是正确的)。
回到用 Python 编写程序:我们基本上只是逐行翻译伪代码。 例如,我们的程序循环应该看起来就像在伪代码中一样:
不需要像代码中那样使用 for 循环。
为了获取输入,我们可以这样做:
现在用户输入存储在变量“response”中,我们可以使用 if 语句(例如“if response == -1:”)来处理可能性。
只需记住在进入 while 循环之前打印说明并将“高”和“低”设置为其初始值,您就应该完成所有设置。
祝你好运!
Welcome to Stack Overflow!
The trick here is to realize that your Python program should look almost like the pseudocode.
First let's try to understand exactly what the pseudocode is doing. If we had to interact with the program described by the pseudocode, it would look something like this:
etc.
When we first think of our number, the program knows only that it is between 1 and 1000. It represents this knowledge by setting the variable 'low' to 1 and the variable 'high' to 1000. Its first guess is the average of these numbers, which is 500.
After we tell the program that our number is greater than 500, it updates the value of 'low' to 501. In other words the program then knows that our number is between 501 and 1000. It then guesses the average of 501 and 1000, which is 750. We tell it that our number is lower, so the program updates the value of 'high' to 749 and guesses the average of 501 and 749 next, and so on until it guesses right, or it has narrowed the possible range down to a single number (meaning its next guess will be right).
So back to writing the program in Python: We basically just translate the pseudocode line for line. For example our program loop should look just like it does in the pseucode:
There is no need for a for-loop as you have in your code.
To take input we can do something like this:
Now the user input is stored in the variable 'response', and we can handle the possibilities with if statements like 'if response == -1:' for example.
Just remember to print the instructions and set 'high' and 'low' to their initial values before entering the while loop and you should be all set.
Good luck!
以下是一些帮助您入门的提示:
平均值 = 值 + 值 + 值 [...] / 值的数量; (例如,((2 + 5 + 3) / (3))
许多编程语言使用不同的运算符优先级。当我编程时,当我不确定运算符优先级时,我总是使用括号。在上面的示例中,如果您只做了 2 + 5 + 3 / 3,程序会在加法之前进行除法运算 - 因此它将计算为 2 + 5 + (3 / 3),或 2 + 5 + 1 == 7。
对于 python 用户请跳过此步骤
/*
其次:您最早的程序可以从 const 正确性中受益(此处很好地解释了它是什么以及为什么它是非常好的实践)。 请仔细阅读并理解为什么应该使用常量(或任何 Python 等效项)。 还要查找“幻数”,这是使用常量的一个大领域。
*/
Google“请原谅我亲爱的莎莉阿姨”(注意:这仅涉及数学运算符,并且大多数适用于编程语言;要更全面地研究运算符优先级,请查找您选择的语言的优先级文档 - 另请注意大多数程序没有内置幂运算符,但大多数标准库都有 pow 函数)。
说到标准库:熟悉标准库函数(我从未使用过Python,我不知道它是如何实现SL的,但如果流行的语言没有完善的SL我会感到非常惊讶)。 如果您不知道那是什么,并且您的书/教程中没有它,请购买一本新的。 任何不引用标准库的资源都不值得花时间。
最后:虽然这篇文章看起来我知道我在说什么,但我确实仍处于学习的早期阶段,就像你一样。 有几件事你可能想尽早习惯(当我跳过这些部分时,它减慢了我的学习速度): 引用和指针的使用(评论问:Python 有指针吗?)、数据之间的差异IN 内存位置和实际内存位置(通常,值在内存中的位置比值本身更有用,至少在写入数据结构时)。 特别是习惯标准库; 寻找在字符串操作中有用的复制、查找等类型函数。
事实上,重读你原来的帖子,我没有意识到这是一个家庭作业类型的作业。 如果你这样做不是为了好玩,你可能永远不会接受我的建议。 请记住,如果您不让它成为一件苦差事,那么编程可以非常有趣 - 并且当您的代码无法编译(或...解释)时,或者您得到意想不到的结果等时,不要感到沮丧。
Here's a few hints to get you started:
Average = Value + Value + Value [...] / Number of Values; (for instance, ((2 + 5 + 3) / (3))
Many programming languages use different operator precedence. When I am programming, I always use parentheses when I am unsure about operator precedence. In my example above, if you only did 2 + 5 + 3 / 3, the program would do division operations before addition - so it would evaulate to 2 + 5 + (3 / 3), or 2 + 5 + 1 == 7.
Skip this for python users
/*
Secondly: your earliest programs can benefit from const correctness (here is a good explanation of what it is and why it is EXTREMELY good practice). Please read through that and understand why you should use constants (or whatever the python equivalent is). Also look up "magic numbers," which is a big area where constants are used.
*/
Google "Please Excuse My Dear Aunt Sally" (NOTE: this only deals with mathematical operators, and mostly holds true for programming languages; for a more comprehensive study of operator precedence, look up your chosen language's documentation for precedence - also note that most programs don't have built in power operators, but most standard libraries have pow functions).
Speaking of standard library: Get acquainted with standard library functions (I have never used Python, I don't know how it implements a SL, but I would be extremely surprised if a language that popular didn't have a well developed SL). If you don't know what that is, and your book/tutorial doesn't have it, get a new one. Any resource that doesn't reference a standard library is not worth the time.
Lastly: while this post may look like I know what I'm talking about, I really am still in the early phases of learning, just like you. A few things you might want to get used to early on (when I skipped these parts, it slowed my learning a lot): The use of references and pointers (Q for comments: does Python have pointers?), the difference between the data IN a memory location and the actual memory location (often times, the location of the value in memory will be more useful than the value itself, at least when writing data structures). Especially get used to the standard library; look for copy, find, etc. type functions useful in string manipulation.
Actually, rereading your original post, I did not realize this was a homework type assignment. If you aren't doing this for fun, you will probably never take my advice. Just remember that programming can be extremely fun, if you don't make it a chore - and don't get frustrated when your code doesn't compile (or...interpret), or you get unexpected results, etc.
在考虑如何用 python(或任何语言)实现这一点之前,让我们看一下伪代码,它看起来是解决问题的一个非常好的计划。
我猜想您可能会遇到的一件事是伪代码引用变量的方式,例如
high
和low
。 理解变量的方法是将它们视为可以存储值的槽。 在任何给定时间,变量都有某个值,例如数字 5 或对打开文件的引用。 该值可以随时通过其名称来调用,也可以通过赋值给它一个新值,旧值将被遗忘,新值将取代它。伪代码引用三个变量:
high
、low
和tries
。 它还告诉您它们的初始值应该是什么。 第二行执行后,这些值分别设置为 1000、1 和 1,但随着程序的进行,它们会采用新值。伪代码的另一个功能是条件循环和用户输入的案例分析。 您对伪代码循环的翻译不正确。 在您的例子中,您创建了一个新变量
i
并指示您的程序使用 1 到 1000 之间的每个 i 值运行循环体。显然,这不需要做太多事情与伪代码。相反,您想要做的是永远循环,直到某些条件(在循环体中发生变化)变为假。 在 python 中,
while
语句执行此操作。 如果您熟悉if
语句,while
看起来是一样的,但在主体完成后,会重新评估条件并再次执行主体(如果满足)仍然如此。最后,循环体中的案例分析需要将某些内容与预期值进行比较。 尽管其他一些语言有多种表达方式,但在 python 中,我们只有
if
-elif
-else
子句。除了将伪代码转换为工作代码之外,了解程序实际在做什么可能很有用。 这里的关键在第 4 行,程序猜测两个值的平均值。 之后,程序会根据猜测的结果进行操作。
在第一次运行循环时,
high
包含 1000,low
包含 1,平均值为 500(实际上平均值为 500.5,但由于我们对整数进行平均) ,python猜测我们希望除法的结果也是一个整数)。 显然,这个猜测正确的可能性只有 0.1%,但如果它是错误的,用户应该告诉我们它是否太高或太低。 不管怎样,这个答案完全消除了 50% 的可能猜测。例如,如果用户想到一个较低的数字,那么当程序猜测 500 时,用户会告诉程序 500 太高,然后程序就不必猜测该数字在范围为 501 到 1000。这可以为计算机节省大量工作。
为了使用该信息,程序会跟踪目标数的可能值范围。 当猜测的数字太高时,程序会向下调整其上限,略低于猜测值;如果猜测值太低,程序会向上调整其下限,略高于猜测值。
当程序再次猜测时,猜测就在可能范围的中间,将范围再次减半。 可能的猜测数量从原来的1000个变成了一次猜测500个,再增加到两次猜测250个。 如果程序运气很差,无法得到两个(实际上很有可能),那么到第三个时,它就只剩下 125 个数字需要担心了。 第四次猜测后,范围内只剩下 62 个数字。 这样继续下去,经过八次猜测后,只剩下 3 个数字,程序将尝试中间的数字进行第九次猜测。 如果结果是错误的,那么只剩下一个数字,程序就会猜测它!
这种将范围分成两半然后继续到更接近的一半的技术称为二分,并且出现在计算机科学感兴趣的广泛主题中。
一些代码怎么样! 因为我不想剥夺您的学习经验,所以我只会给您一些可能对您有所帮助的片段。 python 是一种专为交互式探索而设计的语言,因此请启动您的解释器并尝试一下。 我将发布带有所示提示的示例,但实际上并不需要键入该内容。
以下是使用
while
子句的示例:应通过
raw_input()
函数获取用户的控制台输入。 它只是返回用户输入的任何内容。 这有点难以展示。 为了简化事情,在需要输入的每一行Python之后,我将输入“Hello World!” (不带引号)一些概念的组合怎么样!
哎呀。 那里有一点点错误。 看看能不能修好!
Before thinking about how to implement this in python (or any language) lets look at the pseudocode, which looks like a pretty good plan to solve the problem.
I would guess that one thing you might be getting stuck on is the way the pseudocode references variables, like
high
andlow
. The way to understand variables is to consider them slots that values can be stored. At any given time, a variable has some value, like the number 5, or a reference to an open file. That value can be summoned at any time by using its name, or it can be given a new value by assigning to it, and the old value will be forgotten with the new value taking its place.The pseudocode references three variables,
high
,low
andtries
. It also tells you what their initial values should be. After the second line has executed, those values are set to 1000, 1 and 1, respectively, but they take on new values as the program progresses.Another feature of the pseudocode is a conditional loop, and a case analysis of the user input. Your translation of the pseudocode's loop is incorrect. In your case, you have created a new variable,
i
and have instructed your program to run the loop body with every value of i between 1 and 1000. Obviously this doesn't have a whole lot to do with the pseudocode.Instead what you want to do is loop forever, until some condition (which changes in the loop body) becomes false. In python, the
while
statement does this. If you're familiar with anif
statement,while
looks the same, but after the body is done, the condition is re-evaluated and the body is executed again if it is still true.Finally, the case analysis in the body of the loop requires comparing something to expected values. Although some other languages have a number of ways of expressing this, in python we only have
if
-elif
-else
clauses.Outside of transforming pseudocode to working code, it is probably useful to understand what the program is actually doing. The key here is on line 4, where the program guesses the average of two values. after that the program acts on how well the guess worked out.
In the first run through the loop, with
high
containing 1000 andlow
containing 1, the average is 500 (actually the average is 500.5, but since we're averaging whole numbers, python guesses that we want the result of the division to also be an integer). Obviously that guess has only a 0.1% chance of being right, but if it's wrong, the user is expected to tell us if it was too high, or too low. Either way, that answer completely eliminates 50% of the possible guesses.If, for instance, the user was thinking of a low number, then when the program guessed 500, the user would tell the program that 500 was too high, and then the program wouldn't ever have to guess that the number was in the range of 501 thru 1000. That can save the computer a lot of work.
To put that information to use, the program keeps track of the range of possible values the goal number could be. When the number guessed is too high, the program adjusts its upper bound downward, just below the guess, and if the guess was too low, the program adjusts its lower bound upward to just above the guess.
When the program guesses again, the guess is right in the middle of the possible range, cutting the range in half again. The number of possible guesses went from the original 1000 to 500 in one guess, to 250 in two guesses. If the program has terrible luck, and can't get it two (which is actually pretty likely), then by the third, it has only 125 numbers left to worry about. After the fourth guess, only 62 numbers remain in range. This continues, and after eight guesses, only 3 numbers remain, and the program tries the middle number for its ninth guess. If that turns out to be wrong, only one number is left, and the program guesses it!
This technique of splitting a range in half and then continuing to the closer half is called bisection and appears in a wide range topics of interest to computer science.
How about some CODE! Since i don't want to deprive you of the learning experience, I'll just give you some snippets that might help you along. python is a language designed for interactive exploration, so fire up your interpreter and give this a shot. I'll be posting examples with the prompts shown, don't actually type that.
Here's an example using the
while
clause:Getting console input from the user should be done through the
raw_input()
function. It just returns whatever the user types. This is a little harder to show. To simplify things, after every line of python that requires input, I'll type "Hello World!" (without the quotes)How about some combining of concepts!
Oops. little bit of a bug there. See if you can fix it!
这是一个很大的问题,但是,好吧,让我们一步一步地做! 你的家庭作业开始:
所以您说您不理解任何内容,这意味着您也不理解这部分。 嗯:“用户”是运行你的程序的人。 “说明”是告诉他或她玩游戏该做什么的英语句子,如下引自这份非常清晰且详细的作业:
“
print
”是一条发出信息的Python指令; 例如,尝试一个仅包含的程序,看看它是如何工作的。 好的,您能否编辑您的答案,以向我们表明您已经了解了这一点,以便我们可以转到下一个? 如果我使用的任何单词或概念对您来说仍然太高级,请随时在这里评论并提出进一步的问题,我会尽力澄清!
That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins:
So you don't understand ANY of the stuff, you say, so that means you don't understand this part either. Well: "the user" is the person who's running your program. "Instructions" are English sentences that tell him or her what to do to play the game, as per the following quote from this excellently clear and detailed assignment:
"
print
" is a Python instruction that emits information; for example, try a program containing onlyto see how it works. OK, can you please edit your answer to show us that you've gotten this point, so we can move to the next one? Feel free to comment here with further questions if any words or concepts I'm using are still too advanced for you, and I'll try to clarify!