-3

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)
  • 4
    You're comparing strings to integers. –  Jan 15 '21 at 23:19
  • 2
    i would break it down mathmateically, how would you in a formula calculcate if a user is correct or incorrect then try to code it out. your attempt is good for a novice, but it's what i would expect someone to do if they were working this out manually, i.e with pen and paper. think a little more like a programmer and you'll do better. break it down, google more and you'll do fine. in regards to SO protocol, this doesn't need a [mcve] nor is it a question, it's more of a guidance sort of question which belongs on reddit or another platform. see [ask] and check out the rules. – Umar.H Jan 15 '21 at 23:20
  • 1
    Use `guess1 = int(input("....."))` This will convert the string to integer. Then compare. – Joe Ferndz Jan 15 '21 at 23:38
  • 1
    Above your function, are you initializing each guess variable to one? There is also no point in putting in four parameters if you are going to define them anyway. Just letting you know. – Leonardo Jan 15 '21 at 23:48

2 Answers2

1

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)

enter image description here

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)))

enter image description here

Tấn Nguyên
  • 1,607
  • 4
  • 15
  • 25
1

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:

  1. You don't need 4 variables to store the 4 input values. You can use a list and store all 4 of them there.

  2. 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

  3. Your random.randrange(1,9) will create integers. So you dont have to explicitly convert them back to integer.

  4. 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!
Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33