1

I am trying to see if a user can correctly guess a randomly generated four digit number, by using the in command, but if he gets some digits correct we notify the user.

number=random.randit(1000,9999)
number=str(number)
guess=input("Guess number")
if any (guess in number):
   print("Some digits correct")
newbie
  • 23
  • 3
  • 1
    Possible duplicate of [Find the similarity percent between two strings](https://stackoverflow.com/questions/17388213/find-the-similarity-percent-between-two-strings) – Torxed Oct 07 '17 at 18:22

4 Answers4

0

If you don't require to see of the position of the digit is correct, one way would be to convert both number and guess into sets of digits. For example:

number = 2145
guess = 1078
set(str(number)) & set(str(guess))  # {'1'}

Otherwise, using the built-in difflib might prove useful too.

Hope this helps!

Bart Van Loon
  • 1,430
  • 8
  • 18
0

Once you have created a random number cast it to a string. Once you have casted the number to a string break the users input into an array of characters, then for each character check if the random number contains the users input character. For every character that is guessed correctly increment a variable called correctly guessed. Then you can give a percentage/weight of how correct the user was by dividing the number guessed correctly divided by the array length of input guess.

Oni
  • 84
  • 2
  • You may also want to add some logic for repeating numbers in the randomly generated number for example: Random number: 5556 Guess: 3456 The random number contains both 5 and 6 however not 3 and 4. I am not sure what rules you need to follow but i foresee repeating numbers being a problem if you must meet certain criteria. – Oni Oct 07 '17 at 18:24
0

One way to compare the strings would be to count the occurence of every digit with a Counter:

>>> from collections import Counter
>>> Counter('9993')
Counter({'9': 3, '3': 1})
>>> Counter('3399')
Counter({'3': 2, '9': 2})

You can then iterate from 0 to 9 and find the minimum of the values from both counters:

>>> c1 = Counter('3399')
>>> c2 = Counter('9993')
>>> [(i,min(c1[str(i)], c2[str(i)])) for i in range(10)]
[(0, 0), (1, 0), (2, 0), (3, 1), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 2)]

It means that there is one 3 in common and two 9s.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
0

Your generator has to check for each digit in user guess:

number=randint(1000,9999)
number=str(number)
guess=input("Guess number")
if any (i in number for i in str(guess)):
    print("Some digits correct")
y.luis.rojo
  • 1,794
  • 4
  • 22
  • 41