Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Script gets a terget number from user-1, then gives user-2 multiple chances to "guess" the number
- def get_number(prompt):
- # A utility function to get a valid 3-digit number either as target list, or as a guess list
- while True:
- user_input = input(prompt)
- # Check that string input is of length 3, and is all numeric
- if len(user_input) != 3 or not user_input.isdigit():
- print("Enter a 3-digit number\n")
- continue
- if user_input[0] > "0": # the only other check required is that digit 1 is not zero
- return list(user_input)
- print("Number must be between 100 and 999")
- target_list = get_number("\nEnter a number: ") # Get target number as a list
- while True:
- work_list = target_list.copy() # work_list is a copy of the target number list
- good, close = 0, 0
- guess_list = get_number("\nEnter your guess: ") # get guess as a list
- for i, n in enumerate(guess_list): # process each digit in the guess
- if n == work_list[i]: # does a digit in the guess exist in same position in the target?
- good += 1
- work_list[i] = "x" # prevent target digit from being counted again
- elif n in work_list: # does the guess digit exist elsewhere in the target number?
- close += 1
- # find where the near-miss was in the target
- pos = work_list.index(n)
- work_list[pos] = "x" # prevent target digit from being counted again
- print(f"Correct Place: {good}")
- print(f"Incorrect Place: {close}")
- if good == 3:
- break
- print("You guessed the number. Congrats!")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement