How can I get this python memory game to work - python

This is the code I have so far, my teacher wants the game to "flip the X's over" when you guess a number and when they match the numbers stay but when the numbers are different the numbers "flip back over" and become X's again. And he wants the game to say that "you win" when all the numbers have been exposed.
import random
visual=[['X','X','X','X','X'],['X','X','X','X','X'],['X','X','X','X','X'],['X','X','X','X','X'],['X','X','X','X','X']]
data=[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
random.shuffle(data[0])
random.shuffle(data[1])
random.shuffle(data[2])
random.shuffle(data[3])
random.shuffle(data[4])
while True:
print(visual[0])
print(visual[1])
print(visual[2])
print(visual[3])
print(visual[4])
user_input_1 = int(input('enter a number 0 thru 4 to pick your first X position: '))
user_input_2 = int(input('enter a number 0 thru 4 to pick your first Y position: '))
user_input_3 = int(input('enter a number 0 thru 4 to pick your second X position: '))
user_input_4 = int(input('enter a number 0 thru 4 to pick your second Y position: '))
if data[user_input_1][user_input_2] == data[user_input_3][user_input_4]:
visual[user_input_1][user_input_2] = str(data[user_input_1][user_input_2])
visual[user_input_3][user_input_4] = str(data[user_input_3][user_input_4])
print(visual[0])
print(visual[1])
print(visual[2])
print(visual[3])
print(visual[4])
print('Congratulations you won the game!')
break

Here are the discrete steps in the game as I understand it:
Initialize the board and data.
Shuffle the data
Enter Loop
Print the board
Ask user for their first guess
Ask user for their second guess
Print the board with reveals
Cover them back up if user missed
Check win condition (everything revealed?)
Loop back or print win
Your code successfully initializes the board (step 1), shuffles the data (2), enter loop (3), prints board (4), and asks for the guesses (5)(6).
Here is some guidance on the pieces you are missing:
After you get the inputs, you always want to print the board with the reveals (7). To do this you need to update visuals first with the piece you have written:
visual[user_input_1][user_input_2] = str(data[user_input_1][user_input_2])
visual[user_input_3][user_input_4] = str(data[user_input_3][user_input_4])
and then print your visuals. This does not need to happen with an if statement, because you always want to do a print of the revealed board.
Afterwards, you want to do the swap back to X's if the user misses (8). You have this condition already basically written. You need to check if it's a miss in the data board and swap those visuals back to X's if true:
if data[user_input_1][user_input_2] != data[user_input_3][user_input_4]:
visual[user_input_1][user_input_2] = 'X'
visual[user_input_3][user_input_4] = 'X'
Side Note: Ideally, you want to clear the previous board print of the reveals to test memory. This part is kind of tricky. There are no simple ways to clear the print of the reveals without using operating system commands which are almost certainly beyond the scope of your class. I would check with your teacher about expectations around flipping back over.
If you are interested in how this is achievable using operating system command in Python here is a relevant StackOverflow post. You would need to import os and import time. After you print reveal, use time.sleep(number_of_seconds) to give the user however many seconds to try to memorize placements and then use os.system('clear') for linux/mac os or os.system('CLS') for windows to clear the screen. Again, it's very unlikely that this is what your teacher is looking for.
Now let's deal with the win condition (9). Currently you are using a "while True:" with a break. While this may be functional in this case, using "while True:" should be almost always avoided (there are many reasons why-- here is a post that addresses one reason). Loop structures like "while", "do-while", and "for" have built-in stopping conditions which will be checked each time you loop. In this program, your stopping condition is that the board is completely revealed (that is how you know the game is over and user no longer needs to guess). So, until this happens you want your while loop to keep going. This looks like this:
while #win condition is not met#:
#stuff you want to loop#
#congrats, you have met your win condition#
There are multiple ways to check your win condition is not yet met. One option is that you know you have not won yet if the visual board is still not the same as data board:
while visuals != data:
#stuff you want to loop#
print(congrats....)
In summary, TLDR:
import random
visuals = [...]
data = [...]
#shuffle
while visuals != data:
#print visuals
#get input
#update the inputted visuals with reveals
#print visuals with reveals
if #not a match:
#update the inputted visuals back to X's
print("Congratulations you won the game!")
There are a handful of smaller points that could improve your code as well if you're interested: be very vigilant about indents, a do-while loops is more appropriate here (can you think of why?), you can write functions and loops that reduce a lot of the repeating code (like when you print the visuals). But this should be enough for you to grapple with.

Some suggestions for your code:
Since you display the board so often, you may want to write a separate function that takes the variable visual as input and prints the content. Then you can just call the function instead of writing all of those print statements.
In your current code, you only display the cards when there's a match. One of the whole strategies for playing a memory game is that if you overturn two cards and see "5" and "2" for example, it's not a match, but if you overturn a new pair of cards and one of them is another "5", you might remember where that first "5" was you overturned in your previous turn and thus know how to make a match. So perhaps you should do this: update and display visual after selecting the first card, then do the same with the second card. If there's a match, then leave visual as is. If they don't match, then replace the two spots back with 'X' and go back to the top of the loop.
Your code seems to consider a single match a "win". Shouldn't it be considered won once all of the cards have been matched? In this case, you can follow up the previous step by checking to see if 'X' shows up anywhere in visual. If it doesn't, then that means all of the cards have been uncovered, thus the player has won.

Related

CS50 Final unsatisfied Conditions

I am currently doing my CS50 final project problem and have encountered quite a problem. Below is my code and the error message that appears whenever I give it in. Any help as to how to fix an issue that I'm not sure why is there would be great help. My code works as expected, and runs well. However CS50 just isnt working whenever I try. (Please ignore the README errors as that is just a length problem)
My main problem is that it isnt detecting the 3 functions and the main function and the the whole py thing.
from termcolor import colored
import random
def main():
run_game()
#I have the next couple of functions all put into effect in the run_game function. Therefore only need to do run game.
#This function takes a word to print, and an array containing the colours each letter should be printed input
#The first character in the word will be printed in the first colour in the array and so forth
def present_results(word, colours):
if(len(word)==5 and len(colours) == 5):
print(colored(word[0],colours[0]),
colored(word[1],colours[1]),
colored(word[2],colours[2]),
colored(word[3],colours[3]),
colored(word[4],colours[4]))
else:
print('Invalid input to present_results, word or array incorrect length, both should be length 5')
print('[DEBUG] word length:',len(word),'colour array length:',len(colours))
#The following are tests for the present_results and randint functions
word = "PRINT"
colors = ['green','white','yellow','white','yellow']
#present_results(word, colors)
def generate_word ():
words=['thorn','thick','light','might','cabin','paste','vocal','abode','right','urban','ghost',' zebra',
'grail','tower','brave','crave','chase','image','night','print', 'shame','table','fable','diary','train', 'prick', 'stick', 'slice', 'solid',
'space', 'other', 'about' , 'which', 'witch', 'faith', 'clown', 'scowel', 'towel', 'shelf' , 'stone', 'earth', 'extra', 'adieu', 'entry',
'evict', 'clone', 'shady', 'stock', 'corks', 'actor']
#List of 50 words to pick from
index=random.randint(0,49)
return words[index]
#A lot of words thats returned to be the word that is guessed. its a list and using the random generator it is picked randomly and returned
def letter_in_word (string,letter):
if letter in string:
return True
else:
return False
#Straightforward, whether the letter is present in the word of not it returns true/false
def letter_in_place (string,letter,index):
if string[index]==letter:
return True
else:
return False
#similiar to the top one, if it is in the correct or incorrect spot, it returns true/false
def guess_word (answer,guess):
colors=[]
for i in range(len(answer)):
temp=letter_in_place(answer,guess[i],i)
if temp==True:
colors.append('green')
elif temp==False:
temp=letter_in_word(answer,guess[i])
if temp==True:
colors.append('yellow')
elif temp==False:
colors.append('white')
return guess,answer,colors
#Basically colour cordinated function where in a loop if it follows the placement it is green, the letter is present it is yellow, and if none just white. Using the "in place" function and "letter in word" one too.
def run_game():
answer=generate_word()
for i in range(0,6):
guess=input("Enter a guess: ")
if guess==answer:
print("Great Job,",answer, "is the right word!" )
return
guess,answer,colors=guess_word(answer,guess)
present_results(guess,colors)
print("All 6 Attempts Were Used, Try Again!")
#uses all the above functions and puts it all in one to simplify for the main function.
if __name__ == "__main__":
main()
The code runs well and as expected, however the error that pops up is this:
:) README.md exists
Log checking that README.md exists...
:( final project details
Cause
Description is not long enough.
:| project.py exists
Cause
can't check until a frown turns upside down
:| main function exists
Cause
can't check until a frown turns upside down
:| implemented at least 3 top-level functions other than main
Cause
can't check until a frown turns upside down
EDIT:
Below is a copy paste of my README.MD file its roughly 450 words and is quite long and detailed. I am unsure of the problem. Thank you!
#### Video Demo: <https://youtu.be/jVo5LkGE3Mk>
#### Description:
My name is Karim Osman and I wrote for my final project in CS50s intro to python course a game.
TERMLE is a heavily inspired game from the 2020-2021 hit web browser game called WORDLE. It gained such popularity where it was bought by the New York Times.
It follows a basic concept of the user has six attempts to guess the correct word. The user recieves color-coded hints with each guess indicating a letters presence and position. Green for the letter that is in the correct position and present in the letter. Yellow for incorrect position and present letter. Finally grey for letter is not present in the word.
Following these basic guidelines of WORDLE, I made a similiar game called TERMLE. It uses the same colors and the same concepts with a few minor adjustments. One major difference in that the words present are randomly picked from a list of fifty words within the generate_word function using the random library. From these words there are none that have a duplicate letter, I.E: Eagle - Looks. In addition, the user can play as much as they desire, unlike WORDLE where the user is restricted to one session per day, whether correct or incorrect.
I breifly mentioned the beggining of function above. The generate_word function takes from a list of fifty words, all five letters, and uses the imported random task to return a selected string outside of the function. After so, we have two quite similiar and simple functions called letter_in_place and letter_in_word. The word one sees if the character is present in the returned string, and claims it either as True or False. The place one follows a similiar concept. If the letter is present in the word at a specific placement I.E: "i" is present in brick[2], it will return True, otherwise False.
Using the two above functions we create the next and more important function guess_word. This begins to take into account the placement and present characters in the returned word of the game. Alongside so, it begins color responding to the users input. With the append function, starting with green if the letter and placement is correct it will become true, otherwise it will move to yellow where only the letter is correct, then finally it will go grey where neither the placement or the letter is correct.
Finally, condensing all the above functions into use in the run_game function. This is where the user is prompted an input and the sole call in the main function due to how pratical it is. Prints according to whether the user wins or loses, and uses the presents_results function to properly display the answers.
I am unsure if the formatting is wrong or if I should create it on github and not the project folder. I am very lost here.
I'm pretty sure that the 2nd line (Cause Description is not long enough.) has nothing to do with your code and means 1 of 2 things:
Your README.MD isn't long enough, or
You didn't you follow the instructions about using Markdown syntax under How to Submit .
For reference, my project README word count was 467 and line count was 51. Also, here is the Markdown syntax you need use to to mark your Description.
# YOUR PROJECT TITLE
#### Video Demo: <URL HERE>
#### Description:
TODO

python programming for absolute beginners chapter 3, challenge 4

so I'm having a few thoughts about this challenge. I'm supposed to, instead of guess a number that the program is randomly picking from 1-100 this time myself pick a number randomly and have the program guess it.
So I made it work but its not exactly what I want it to be, here is what I got so far tho:
#I'm deciding to go with number 43.
import random
print("Hello computer, welcome to my guessing game!")
guess_list=[]
computer_guess=""
tries=1
while computer_guess!=43:
computer_guess =(random.randint(1, 100))
if computer_guess in guess_list:
continue
elif computer_guess==43:
break
else:
print("Is the number you're thinking of ",computer_guess,"?")
guess_list.append(computer_guess)
tries+=1
print("I finally got it! Your number was 43 and it only took me",tries,"tries!")
I kind of wanted to make it so that, based on what I reply the program understands( and repicks a number ) diffrently.
Basiclly I tried adding this:
if response=="I'm thinking of a higher number, keep guessing!":
computer_guess=(random.randint(int(computer_guess),100))
if response=="I'm thinking of a lower number, keep guessing!":
computer_guess=random.randint(1,int(computer_guess))
My thought was to answer based on its previous guess and have it correct itself("too high, or "too low"). I do understand I cant have computer_guess inside of computer_guess, but I'm not sure what to do here. If its worht mentioning I'm doing this on my sparetime so sadly I dont have any professor to ask on the subject.
Should I just keep it simple or is it easy making this adjustment?
Thanks,
Etil
Well, the computer must guess whatever numbers, the easiest solution would be for the computer to guess 1, if that isn't correct then guess 2 etc, but that would mean traversing all the numbers and asking n times the user for an answer (quite annoying).
FIRST: I would change your hardcoded 43 for a number that you choose.
THEN: You can make your program guess 1 by one (That works)
THEN: Explore more efficient solutions (e.g go to (max+min/2) and ask the user if higher, equal etc if higher reset your min to be ((max+min)/2) and do not touch max, if lower reset your max to be max+min/2 and repeat.
That is also way more efficient as you don't have to keep track of what the computer guessed, eventually it would get there.
Hope that helps!

in a while loop, where should you place a variable for counting?

enter image description here
Please excuse me that I'm posting my code as an image.
This is a simple guessing game expression.
When you look at the last line of the code,
there is 'tries += 1' code to count how many times it's looped.
So my question is,
the result is changing when I put 'tries += 1' right under
the code line 'guess = input("What is your lucky number?")'.
So what is the difference between
putting it at the last line of the code block and right under the start of while loop code.
Thanks for helping :)
Wouldn't it have been far easier to just copy in the text than to print-screen and crop the image? The number of tries is initialized to 1 which is misleading as at that point in the program there hasn't been any tries. Logically it makes more sense to initialize tries to 0 and place the increment immediately after the user input. But because the program hasn't been structured in this way, tries must be incremented after comparing the guess to the target; otherwise, in the case when the user's guess is correct, the output would show a number of tries one greater than the actual number of tries.
What you're misunderstanding is the order in which your code executes. There are three important events inside your loop:
You ask the user for their guess
You process their guess, and if they get it right you display the current value of the variable tries
You increment the variable tries, in the statement tries += 1
These execute in exactly that order. So, when the user guesses correctly, they're told the value of tries before it is incremented again. If you put the line tries += 1 right after the input statement, then that value is now being increased before it is printed. Thus, the displayed value is different.

Beginner Python Area of a room

Right now I am working on a program to calculate the area of a room in order to purchase cans of paint. I am just a three weeks into my class and I'm a little overwhelmed. I'm having trouble figuring out how I am supposed to attach each wall/ceiling/window/door to a separate name such as 'WALL1 WALL2' etc and then being able to call those to a calculation. As far as I have gotten I can't seem to figure out how to write this variable. I am by no means asking for the code to the whole program, so we will take a look at just walls as an example. "John wants to calculate how much paint he needs for a whole house and has 57 walls with various sizes of each wall." How do I allow an unlimited amount of walls to be used while attaching each wall to its Length and Height? Or should I limit the amount of walls? Once I establish how many of these walls there are how do I attach each wall to its own name? Each 'name' will then be called into the final calculation. Here is what I have so far:
# Area calculation for paint program
print "Area Calculation For Paint"
Project_Name = input('Enter your Project Name:')
print "WALL1."
print "WALL2."
print "WALL3."
print "WALL4."
print "WALL5"
print "WALL6"
print "WALL7"
print "WALL8"....
# Get the user’s choice:
shape = input("Please select a Wall and input the length and height: ")
# Calculate the area for each room
if WALL1 == yes:
height = input("Please enter the height: ")
length = input("Please enter the length: ")
area1 = height*length
WALL1 = area1
# Calculate the total square footage
TOTALSQFT = WALL1 + WALL2 + WALL3 + WALL4 + WALL5 + CEILING1 - WINDOW1 + WINDOW2 + WINDOW3 + DOOR1 + DOOR2... etc
print "Project_Name total square footage is TOTALSQFT"
I have provided my Flowchart here as reference so hopefully it makes better sense what I am trying to explain.
You can use a list or a tuple to store your walls ceiling etc. then its a matter of running a For loop to do the calculation. You may also want to use a dictionary if you want to call the items by name.
You can create Wall1, Wall2 etc using a simple string addition and put that in the dictionary rather than creating variables for each element.
If you clarify how you gonna accept the user input for all 57 walls etc. we can answer more accurately.
After our discussion in the comments, it appears that your real problem comes from not really understanding the relative difficulty of things yet. In large part that's because you don't really understand programming yet, you've just been making flowcharts in your class. There's a fair difference between flowcharts and programming, since with a flowchart you can just put something magic happens.
My first recommendation is to check out the Python style guide, called pep8).
Most Python developers stick to this, and it will make your life easier when trying to communicate with us.
Next, you want to adjust your expectations. Trying to parse out a bunch of values from something like:
Wall 1 3x4 Wall 2 5x9 Wall 3 9x9 Door 1 2x6.5 Door 2 2x6.5
You can do it, but as a beginning developer it's a bit overwhelming. If you know regular expressions it's pretty trivial, but you don't, and they're not a beginning topic. Just remember the popular saying:
Developers see a problem and say, "Ah, I know, I'll use regular expressions!" Now they have two problems.
Most of the time they're the wrong thing, but occasionally they're the right thing. But as a beginner, they're not the right thing.
Instead, you should aim for something like this:
get the project name
ask the user for wall sizes. When they input an empty/blank string, that's the last wall size
ask the user for ceiling sizes (though you could include this in the wall sizes, no need to have them different). When they input an empty/blank string there are no more ceilings.
ask the user for the door sizes. Same thing about empty strings.
ask the user for window sizes. The same thing applies for ceiling vs walls.
combine the wall/ceiling sizes and subtract (door sizes + window sizes)
You can store the sizes in lists, e.g. walls = [[3, 4], [5, 9], [9, 9]]. Dealing with lists is something that you can learn in the Python tutorial, or many other tutorials on the Internet.
You can iterate (loop) over your lists and write that information to a file, if that's something that you want to do. Tutorials will also cover that.
If you take the above approach, you'll find that your project is much easier to complete. Good luck!
Have you considered using pandas data frames to store each instance of Wall, Window and Ceiling? Then you multiply your columns Width by Length and store it in the column Surface.
Then you can simply use the groupbyfunction to get your totals and add up the results, or simply sum the Surfacecolumns.

Transform game pseudo code into python

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!
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 and low. 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 and tries. 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 an if 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 and low 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:
>>> x = 1000
>>> while x > 1:
... x = x/2
... print x
...
500
250
125
62
31
15
7
3
1
>>> x
1
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)
>>> raw_input()
Hello World!
'Hello World!'
>>> y = raw_input()
Hello World!
>>> print y
Hello World!
>>>
How about some combining of concepts!
>>> myvar = ''
>>> while myvar != 'exit':
... myvar = raw_input()
... if myvar == 'apples':
... print "I like apples"
... elif myvar == 'bananas':
... print "I don't like bananas"
... else:
... print "I've never eaten", myvar
...
apples
I like apples
mangoes
I've never eaten mangoes
bananas
I don't like bananas
exit
I've never eaten exit
>>>
Oops. little bit of a bug there. See if you can fix it!
I don't understand any of this stuff at all!
That's pretty problematic, but, fine, let's do one step at a time! Your homework assignment begins:
Print instructions to the user
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:
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.
"print" is a Python instruction that emits information; for example, try a program containing only
print "some information"
to 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!
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:
high = 1000
low = 1
print "Pick a number between 1 and 1000."
print "I will guess your number in 10 tries or less."
print "Or at least i'll try to. ;)"
print "My first guess is 500."
guess = 500
tries = 0
answer = 1
print "Enter 1 if it's higher."
print "Enter -1 if it's lower."
print "Enter 0 if I guessed it!"
print ""
while (answer != 0):
answer = int(raw_input("Am I close?"))
if answer == 1:
tries = tries + 1
low = guess
guess = (high + low) / 2
print "My next guess is:"
print guess
elif answer == -1:
tries = tries + 1
high = guess
guess = (high + low) / 2
print "My next guess is:"
print guess
elif answer == 0:
tries = tries + 1
print "Your number is:"
print guess
print "Yay! I got it! Number of guesses:"
print tries
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
high=23
low=7
then compute what you think should be the average or midpoint between them (hint: 15)
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:
Think of a number between 1 and 1000 and press Enter.
>>>
Is it 500? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
>>> 1
Is it 750? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
>>> -1
Is it 625? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.
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:
while high > low:
# Guess (high + low) / 2 and ask user to respond
# Handle user response
There is no need for a for-loop as you have in your code.
To take input we can do something like this:
guess = (high + low) / 2
response = input('Is it ' + str(guess) + '? Enter -1 if it's lower, 0 if I guessed right, or 1 if it's higher.')
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!
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.

Categories

Resources