Check if userinput matches any digits of a (random) integer - python

random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
guess = int(input("That was incorrect! Enter your guess: "))
This works as a very simple guessing game, however I would like to include something where after every unsuccessful try it would say how many numbers out of the four digit number were correct.
I have not attempted this, mainly because I'm not sure how this could be done.
e.g
random = 1234
Enter your guess: 1111
You guessed 1 number correct
Enter your guess: 1222
You guessed 2 numbers correct
...... and so on

If you meant with positions
random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
right = 0
index = 0
for char in str(guess):
if char == str(random)[index]:
index += 1
right += 1
print(f'{right} were right')
guess = int(input("That was incorrect! Enter your guess: "))

If you really wanted to keep both numbers as int, you could use % (modulo operator) to find the remainder of your integer once divided by its base-10 value.
For example.
correctnum = 0
random = 1234
guess = 1111
if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
correctnum++
Formula repeated for 100/10/1 should all compare numbers in that "spot" without having to convert datatypes. Follow that up with an output of the value of correctnum and you should have what you need.

random = 1234
random = str(random)
#guess = str(input('enter your guess'))
guess = '1222'
correct = 0
for i in range(len(guess)):
if guess[i] == random[i]:
correct += 1
print(correct)
ouput: 2
or simply:
correct = sum(guess[i] == random[i] for i in range(len(guess)))

Related

How to make a deductive logic game of guessing a three degit number?

The question is: In Bagels, a deductive logic game, you must guess a secret three-digit number based on clues. The game offers one of the following hints in response to your guess: “Pico” when your guess has a correct digit in the wrong place, “Fermi” when your guess has a correct digit in the correct place, and “Bagels” if your guess has no correct digits. You have 10 tries to guess the secret number.
I am new in Python. Any suggestions are appreciated:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
for i in range(10):
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
input_dictionary = dict(zip(range(len(input_list)), input_list))
if random_number == input_num:
print("Your answer is correct!!")
break
elif [i for (i, j) in zip(rand_list, input_list) if i == j]:
print("Fermi")
if set(rand_list) & set(input_list):
print("Pico")
elif set(rand_list) & set(input_list):
print("Pico")
else:
print("Bagels")
else:
print("This is not a valid three digit number. Please try again.")
print("The test is finished.")
I don't know if i got what you wanted but try this:
#Generating a random 3-digit number
import random
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
random_number=random_with_N_digits(3)
print(random_number)
#Making a dictionary From the integers of the number
#Indexes as Keys and integers as values
rand_list = [int(x) for x in str(random_number)]
rand_dictionary=dict(zip(range(len(rand_list)),rand_list))
#rand_dictionary
#For loop for 10 tries
i = 0
while i < 10:
try:
input_num = int(input('Please guess that three digit number : '))
#Validating the input
if input_num < 999 and input_num > 100:
#Making dictionary for the inputted number in similar way like the random number
input_list = [int(x) for x in str(input_num)]
print(input_list)
input_dictionary = dict(zip(range(len(input_list)), input_list))
if input_num == random_number:
print("Your answer is correct!!")
break
elif set(rand_list) & set(input_list):
correct_place = 0
for j in range(0, len(input_list)):
if rand_list[j] == input_list[j]:
correct_place += 1
correct_digits = len(set(rand_list) & set(input_list))
print("Fermi "*correct_place + "Pico "*(correct_digits - correct_place))
else:
print("Bagels")
i += 1
else:
print("This is not a valid three digit number. Please try again.")
except:
print("Not a valid input")
print("The test is finished.")

Guess 4 digit combination game

I am trying a similar thing like this: 4 Digit Guessing Game Python . With little changes.
The program generates random numbers between 999 and 10000.User after every failed attempt gets how many numbers he guess in the right spot and how many numbers he got right but didn't guess position correctly.
Etc. a random number is 3691 and the user guess is 3619. He gets 2 numbers in the correct position (3 and 6) and also 2 numbers correct but in the wrong position (1 and 9).
There is no output when for numbers he didn't guess and guessing is repeating until all 4 digits are guessed in the right spot.
My idea is we save digits of the random number to a list and then do the same thing with user guess number. Then we compare the first item of both lists etc. combination_list[0] == guess_ist[0] and if it's correct we add +1 on counter we call correct.
The problem is I don't have an idea for numbers that are guessed correctly but are not in the correct position.
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination, digits_guess= [], []
temp = combination
while temp > 0:
digits_combination.append(temp % 10)
temp //= 10
digits_combination.reverse()
print(digits_combination)
guess= int(input("Your numbers are? "))
while not 999 < pokusaj < 10000:
pokusaj = int(input("Your numbers are? "))
if guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess//= 10
digits_guess.reverse()
if guess == combination:
print("Your combination is correct.")
correct_position= 0
correct= 0
test = digits_combination[:] # I copied the list here
while guess!= combination:
while guess> 0:
digits_guess.append(guess% 10)
guess //= 10
digits_guess.reverse()
if digits_guess[0] == test[0]:
correct_position += 1
I have this solution. I suggestion you to cast to string and after cast to list to get a list of number digits instead to use a while loop. For the question you can try to use "in" keywords to check if number in digits_combination but not in right position.
import random
combination = random.randint(1000, 9999)
print(combination)
digits_combination = list(str(combination))
guess= int(input("Your numbers are? "))
while not 999 < guess < 10000:
guess = int(input("Your numbers are? "))
digits_guess = list(str(guess))
if guess == combination:
print("Your combination is correct.")
correct_position = 0
correct = 0
for index, value in enumerate(digits_guess):
if value == digits_combination[index]:
correct_position += 1
elif value in digits_combination:
correct += 1

Trouble with an assignment

I am doing an assignment for school where I need to make a list and assign 4 random integers to the list between 1 and 9. Then, I need to prompt the user for what their guess is for each value. If they get any of the numbers right, I need to say how many, but I've been working on this for like 3 hours and I'm getting nowhere. Currently, all I have is a massive useless nested if/elif statements.
This is the assignment prompt:
Program Specifications:
Computer should generate 4 random numbers from 1 - 9 as the "Secret Code".
User should be prompted for their guess of those four numbers.
After they provide their full guess, the user is told how many are correct.
As long as the user does not get all four correct, they keep getting asked for their guess.
After the user finally gets all of them correct (yes - all four), they are congratulated and then told how many tries it took them.
Technical Requirements:
Use at least one list
Use at least one function with parameters
I'm so confused and I don't know where to start. Here is my current code:
import random
count = 0
guess1 = 1
guess2 = 1
guess3 = 1
guess4 = 1
def getGuess(count,guess1,guess2,guess3,guess4):
while True:
guess1 = input("What is your guess for the first number? ")
guess2 = input("What is your guess for the second number? ")
guess3 = input("What is your guess for the third number? ")
guess4 = input("What is your guess for the fourth number? ")
if str(guess1) == numbers[0] and str(guess2) == numbers[1] and str(guess3) == numbers[2] and str(guess4) == numbers[3]:
print("Your first, second, third, and fourth numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1] and guess3 == numbers[2]:
print("Your first, second, and third numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1]:
print("Your first and second number are correct!")
elif guess1 == numbers[0]:
print("Your first number is correct!")
elif guess2 == numbers[1]:
print("Your second number is correct!")
elif guess2 == numbers[1] and guess3 == numbers[2]:
print("Your second and third numbers are correct!")
elif guess2 == numbers[1] and guess3 == numbers[2] and guess4 == numbers[3]:
print("Your second, third, and fourth numbers are correct!")
elif guess3 == numbers[2]:
print("Your third number is correct!")
elif guess3 == numbers[2] and guess4 == numbers[3]:
print("Your third and fourth numbers are correct!")
elif guess4 == numbers[3]:
print("Your fourth number is correct!")
else:
print("None of your numbers are correct. Try again.")
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
print(numbers)
getGuess(count,guess1,guess2,guess3,guess4)
I see your attempt so I'm going to tell you the problems, as comments said:
Logic flow: your if else statement are serving 4 numbers, what if 10, 100 numbers? It should be generic
You are comparing string with integer, should cast it
Should package your variables inside your function. Which is very ambiguous of guess1 = 1, guess1 function variable, guess1 from input,...
Init random numbers
import random
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
getGuess function, which is getting guess numbers from input string, then split it and convert to int.
def getGuess(numbers):
retryCount = 0
while True:
# You can put try catch here for number validation
guessNums = [int(x) for x in input("Numbers: ").split()]
# To make sure your input must be the same length
if len(guessNums) != len(numbers):
print('Not available numbers')
continue
# Here we just check for incorrect, once it's met, the for loop will be broken and go to the next while loop
isIncorrect = False
for index, num in enumerate(numbers):
if num != guessNums[index]:
isIncorrect = True
retryCount += 1
print('Order of ' + str(index + 1) + ' is incorrect')
break
# When every number is equal, not incorrect occured, return retry count
if isIncorrect == False:
return retryCount
Using:
print('Your retry count: ' + str(getGuess(numbers)))
You can optimize many of the parts of your code.
Assumption: You know how to use lists as you are already using numbers as a list. I am staying away from dictionary. Not sure if you know its use. Also assume you understand list comprehension. If you dont, see this link on list comprehension.
Now let's look at your code. Here are a few things to consider:
You don't need 4 variables to store the 4 input values. You can use a list and store all 4 of them there.
As many have already suggested, you should convert the input value into an integer. When you convert string to integer, there is a potential that the string is not an integer. This can result in code getting broken. So use Try Except to catch the error while converting to int
Your random.randrange(1,9) will create integers. So you dont have to explicitly convert them back to integer.
You have 4 inputs and 4 values to compare. You can map each value to the position and compare. That will reduce the complexity. For the ones that are successful, keep a tab of it. Then print the ones that matched. Again, this can be done using a list or dictionary.
With all that to consider, I have re-written your code as follows. See if this helps you with the solution.
import random
nums = [random.randrange(1,9) for _ in range(4)]
def getGuess():
g = ['first','second','third','fourth']
i = 0
gx = []
while i<4:
try:
x = int(input(f"What is your guess for the {g[i]} number? :"))
gx.append(x)
i+=1
except:
print ('Not numeric, please re-enter')
gwords = [g[i] for i in range(4) if nums[i] == gx[i]]
if gwords:
if len(gwords) == 1:
resp = "Your " + gwords[0] + ' number is correct!'
else:
resp = "Your " + ', '.join(gwords[:-1]) + ' and ' + gwords[-1] + ' numbers are correct!'
print (resp)
else:
print ("None of your numbers are correct. Try again.")
getGuess()
Here's an example run of the above code:
What is your guess for the first number? :1
What is your guess for the second number? :6
What is your guess for the third number? :5
What is your guess for the fourth number? :4
Your second, third and fourth numbers are correct!

Comparison between the same values is always false

import random
def g1to9():
a = random.randint(1,9)
wt = 0
b = input("Guess a number from 1 to 9:")
if a == b:
print("You guessed it correctly, it took you {} tries".format(wt))
while True:
if a != b:
print("You are wrong!")
b = input("Guess a number from 1 to 9:")
wt += 1
I am trying to create a game "Guess a number from 1 to 9". But when I run it I check all the numbers but a is never equal to b. I tried to make a a global variable,but it didn't work. What's wrong with my code?
b would of type str as it is an input. You need to cast it to an int first. You can do that by:
b = int(input("Guess a number from 1 to 9:"))

Guess Random Number Why i m not able to enter input - python

Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).

Categories

Resources