chevron_left chevron_right
Login Register invert_colors photo_library


Stay updated and chat with others! - Join the Discord!
Thread Rating:
  • 0 Vote(s) - 0 Average


Legends Python Challenge #2: Guessing The Number filter_list
Author
Message
Python Challenge #2: Guessing The Number #1
This is usually a good beginner challenge. And maybe for m0dem to write it in half the lines I do.

Create a program that lets the user guess a random number. If the guess is too high or too low, tell them. The game should keep track of the number of wrong answers and display how many guesses it took to complete. The user should also have the option of replaying the game after winning.

*ADVANCED VERSION*
Make it so you set the number and the computer needs to guess it.

My reg version:
Spoiler:
Code:
import random

def guess_check():
    random_number = random.randint(1, 100)
    guesses = 0
    guess = int(input('Guess the number: '))
    while guess != random_number:
        guesses+=1
        if guess > random_number:
            print('Too high, try again. ')
            guess = int(input('Guess the number: '))
        elif guess < random_number:
            print('Too low, try again. ')
            guess = int(input('Guess the number: '))
    if guess == random_number:
        guesses+=1
        print('Congratulations! You guessed the number in',guesses, 'guesses.')

def start_over():
    play_again = input('Do you want to play again? (Y or N) ')
    while play_again.lower() == 'y':
        guess_check()

guess_check()
start_over()

Advanced Version:
Spoiler:
Code:
import random

correct_number = int(input('Enter a number for the computer to guess (1 - 100): '))
guesses = 0

def computer_guess(correct_number, guesses):
    comp_guess = random.randint(1, 100)
    guesses += 1
    print('The computer guessed', comp_guess)
    while correct_number > comp_guess:
        print('Too low!')
        comp_guess = random.randint(comp_guess +1, 100)
        print('The computer guessed', comp_guess)
        guesses += 1
    while correct_number < comp_guess:
        print('Too high!')
        comp_guess = random.randint(1, comp_guess - 1)
        print('The computer guessed', comp_guess)
        guesses += 1
    else:
        print('The computer guessed the number in', guesses, 'attempts!')

computer_guess(correct_number, guesses)


When you're boss af:
[Image: acb7ac1c047a1738079ea3061452bdfa.png]

[+] 1 user Likes Nil's post
Reply

RE: Python Challenge #2: Guessing The Number #2
I'm not really a code golf kind of guy, so I don't usually shoot for the smallest code.
Thanks for the challenge! Smile
Code:
import random

def main():
    guesses = 0
    num = random.randint(1, 100)
    print("Guess a number from 1 to 100.")
    while True:
        guesses += 1
        guess = int(raw_input("> "))
        if guess > num:
            print("Too high.")

        elif guess < num:
            print("Too low.")

        elif guess == num:
            print("You guessed the right number in {} tries!".format(guesses))
            break


while True:
    main()
    print("Do you want to try again? (y/n)")
    if raw_input("> ").lower() == "n":
        break

Quote:*ADVANCED VERSION*
Code:
import random

def inRange(num, low, high):
    if num < low or num > high:
        return False

    return True

def mainA():
    low = 1
    high = 100
    print("Choose a random number between {} and {}.".format(low, high))
    num = low - 1
    while not inRange(num, low, high):
        num = int(raw_input("> "))
        
    guesses = 0
    cRange = [1, 100]
    print("Computer, guess a number from 1 to 100.")
    while True:
        guesses += 1
        # computer algorithim
        guess = int((cRange[1] - cRange[0]) / 2) + cRange[0]
        print("> {}".format(guess))
        if guess > num:
            print("Too high.")
            cRange[1] = guess

        elif guess < num:
            print("Too low.")
            cRange[0] = guess

        elif guess == num:
            print("The computer guessed our number in {} tries!".format(gueses))
            break

while True:
    main()
    print("Do you want to try again? (y/n)")
    if raw_input("> ").lower() == "n":
        break

[+] 1 user Likes m0dem's post
Reply

RE: Python Challenge #2: Guessing The Number #3
(12-16-2015, 11:31 PM)m0dem Wrote: I'm not really a code golf kind of guy, so I don't usually shoot for the smallest code.
Thanks for the challenge! Smile
Code:
import random

def main():
    gLeft = 8
    num = random.randint(1, 100)
    print("Guess a number from 1 to 100.")
    while gLeft > 0:
        gLeft -= 1
        guess = int(raw_input("> "))
        if guess > num:
            print("Too high.")

        elif guess < num:
            print("Too low.")

        elif guess == num:
            print("You guessed the right number in {} tries!".format(8 - gLeft))
            return

    print("All your tries are gone.")

*ADVANCED VERSION*
Code:
import random

def inRange(num, low, high):
    if num < low or num > high:
        return False

    return True

def mainA():
    low = 1
    high = 100
    print("Choose a random number between {} and {}.".format(low, high))
    num = low - 1
    while not inRange(num, low, high):
        num = int(raw_input("> "))
        
    gLeft = 8
    cRange = [1, 100]
    print("Computer, guess a number from 1 to 100.")
    while gLeft > 0:
        gLeft -= 1
        # computer algorithim
        guess = int((cRange[1] - cRange[0]) / 2) + cRange[0]
        print("> {}".format(guess))
        if guess > num:
            print("Too high.")
            cRange[1] = guess

        elif guess < num:
            print("Too low.")
            cRange[0] = guess

        elif guess == num:
            print("The computer guessed our number in {} tries!".format(8 - gLeft))
            return

    print("The computer failed to guess the correct number!")

Nice. Haven't looked at your second code since I still haven't done it Tongue

But, for your first one you should have set it so the user can play an unlimited amount of times rather than setting it to 8 games. Maybe I was a bit unclear or you just forgot. All good.

Reply

RE: Python Challenge #2: Guessing The Number #4
(12-16-2015, 11:42 PM)God Wrote: Nice. Haven't looked at your second code since I still haven't done it Tongue

But, for your first one you should have set it so the user can play an unlimited amount of times rather than setting it to 8 games. Maybe I was a bit unclear or you just forgot. All good.

Oh, woops! xD
Sorry about that; I have now updated my code.
Tip on making computer algorithms: Make the computer do what you would do... that is, if you play strategically xD

Reply

RE: Python Challenge #2: Guessing The Number #5
Code:
import random
def g():
    r = random.randint(1,100)
    gc = 0
    g = int(raw_input("Guess a number between 1 and 100: "))
    while g != r:
        gc+=1
        if g > r:
            g = int(raw_input("Try going lower, guess a number between 1 and 100: "))
        if g < r:
            g = int(raw_input("Try going higher, guess a number between 1 and 100: "))
    if g == r:
        gc+=1
        gc = str(gc)
        r = str(r)
        print('You guessed the number '+r+' in '+gc+' guesses.')
def a():
    a = raw_input("Would you like to play again? [y/n] ")
    if a == "y":
        g()
g()
a()

(12-16-2015, 08:04 PM)God Wrote: My reg version:
Spoiler:
Code:
import random

def guess_check():
    random_number = random.randint(1, 100)
    guesses = 0
    guess = int(input('Guess the number: '))
    while guess != random_number:
        guesses+=1
        if guess > random_number:
            print('Too high, try again. ')
            guess = int(input('Guess the number: '))
        elif guess < random_number:
            print('Too low, try again. ')
            guess = int(input('Guess the number: '))
    if guess == random_number:
        guesses+=1
        print('Congratulations! You guessed the number in',guesses, 'guesses.')

def start_over():
    play_again = input('Do you want to play again? (Y or N) ')
    while play_again.lower() == 'y':
        guess_check()

The only thing your code does right there is define functions. Nothing is actually running.
Either way, when someone guesses the number, it prints
Code:
('Congratulations! You guessed the number in', x, 'guesses.')
You can fix that by converting "guesses" to a string then concatenating it normally.

Also, if someone enters N or Y whenever the script asks if they want to play again, it'll just throw them an error. That's how it behaves in command prompt at least.
(This post was last modified: 12-17-2015, 04:28 AM by meow.)

[+] 1 user Likes meow's post
Reply

RE: Python Challenge #2: Guessing The Number #6
(12-17-2015, 04:23 AM)meow Wrote:
Code:
import random
def g():
    r = random.randint(1,100)
    gc = 0
    g = int(raw_input("Guess a number between 1 and 100: "))
    while g != r:
        gc+=1
        if g > r:
            g = int(raw_input("Try going lower, guess a number between 1 and 100: "))
        if g < r:
            g = int(raw_input("Try going higher, guess a number between 1 and 100: "))
    if g == r:
        gc+=1
        gc = str(gc)
        r = str(r)
        print('You guessed the number '+r+' in '+gc+' guesses.')
def a():
    a = raw_input("Would you like to play again? [y/n] ")
    if a == "y":
        g()
g()
a()


The only thing your code does right there is define functions. Nothing is actually running.
Either way, when someone guesses the number, it prints
Code:
('Congratulations! You guessed the number in', x, 'guesses.')
You can fix that by converting "guesses" to a string then concatenating it normally.

Also, if someone enters N or Y whenever the script asks if they want to play again, it'll just throw them an error. That's how it behaves in command prompt at least.

Yeah It's supposed to have guess_check() and start over() at the end of the code but I must have forgotten to copy and paste to the end. I'll edit it so it runs. Thanks.

As for your other comments, it might be because you're running an earlier version of Python? It works fine for me in both command prompt and the python shell.

Reply

RE: Python Challenge #2: Guessing The Number #7
(12-17-2015, 08:08 AM)God Wrote: Yeah It's supposed to have guess_check() and start over() at the end of the code but I must have forgotten to copy and paste to the end. I'll edit it so it runs. Thanks.

As for your other comments, it might be because you're running an earlier version of Python? It works fine for me in both command prompt and the python shell.

Ah yeah you're probably right. I'm using Python 2.7.11.

Reply

RE: Python Challenge #2: Guessing The Number #8
Well, finally got around to the advanced version. Wasn't much of an advanced version looking back at it. I don't code often and I didn't see it as too much more difficult than the regular version.

Code:
import random

correct_number = int(input('Enter a number for the computer to guess (1 - 100): '))
guesses = 0

def computer_guess(correct_number, guesses):
    comp_guess = random.randint(1, 100)
    guesses += 1
    print('The computer guessed', comp_guess)
    while correct_number > comp_guess:
        print('Too low!')
        comp_guess = random.randint(comp_guess +1, 100)
        print('The computer guessed', comp_guess)
        guesses += 1
    while correct_number < comp_guess:
        print('Too high!')
        comp_guess = random.randint(1, comp_guess - 1)
        print('The computer guessed', comp_guess)
        guesses += 1
    else:
        print('The computer guessed the number in', guesses, 'attempts!')

computer_guess(correct_number, guesses)

Criticism is welcome.
"If you look for the light, you can often find it. But if you look for the dark, that is all you will ever see.”


Reply

RE: Python Challenge #2: Guessing The Number #9
python2 (since there's py3 submissions, and discrepancies are annoying):
Code:
from random import randint

num=randint(1,10)
while 1:
    n=input('guess number: ')
    if num==n: break
    elif num<n: print 'too high'
    else: print 'too low'

print 'correct!'

Reply

RE: Python Challenge #2: Guessing The Number #10
Pretty sure that the best way for the computer to guess in the advanced version is by a sort of binary chop algorithm, which is sort of what I've done.

Code:
def aiguess(remaining):
    mid = int((remaining[0]+remaining[1])/2)
    return mid

num = int(input("Set the number (Between 1 and 100): "))
while num > 100 or num < 0:
    num = int(input("Set the number (Between 1 and 100): "))

guesses = 0
remaining = [0,100]
done = False
while done != True:
    guess = aiguess(remaining)
    print("The computer guessed: ",guess)
    if guess < num:
        print("You tell the computer that it is higher than its guess.")
        remaining[0] = guess + 1
        guesses += 1
    elif guess > num:
        print("You tell the computer that it is lower than its guess.")
        remaining[1] = guess - 1
        guesses += 1
    else:
        guesses += 1
        done = True
print("The computer guessed your number in ",guesses," guess(es)!")

Reply






Users browsing this thread: 1 Guest(s)