Reputation: 31
I'm not really sure how to go about this but I'm trying to make a guessing game and give feedback on the user's input. For example if the number to be guessed is 6709 and the user inputs 6908 the input would be wrong but still partially correct. If one portion of the integer is correct the program will tell the user it's correct and do the same if its wrong.
Lets says the number to be guessed is 6709
And the user inputs 6908
The program would produce a output like this (Yes No Yes No)
What would be the method to split an integer into portions so that I could give feedback? Or is there a decimal place technique for this?
Upvotes: 0
Views: 161
Reputation: 1953
It's been documented here that an easy way to approach this is to treat the integers like strings, but I thought it might be fun to show an approach that refrained from converting the integers to strings.
You could write a method that takes an integer argument and returns a list of the digits. It might look something like this:
def get_digits(num):
digits = []
while num > 0:
digits.insert(0, num % 10)
num /= 10
return digits
Note that you'll need to use the //=
operator for integer division if you're using Python 3.
So in order to get the list of yes
and no
values for two integers, you could do this:
def get_element_wise_equality(a, b):
# a and b are integers
digits_a = get_digits(a)
digits_b = get_digits(b)
if len(digits_a) != len(digits_b):
return None
result = []
for i in range(len(digits_a)):
if digits_a[i] == digits_b[i]:
result.append('yes')
else
result.append('no')
return result
Upvotes: 0
Reputation: 1590
I think you would be best off converting the numbers to strings and then comparing each character:
userInput = 6908
answer = 6709
userInputStr = str(userInput)
answerStr = str(answer)
outputStr = " "
print(outputStr.join(["Y" if i == j else "N" for i, j in zip(userInputStr, answerStr)]))
Upvotes: 0
Reputation: 3417
Actually, there's an even simpler solution than any of these: convert number to list
import numpy as np
num1 = 1234
num2 = 1245
a = list(str(num1))
b = list(str(num2))
// a = [1,2,3,4]
// b = [1,2,4,5]
c = np.in1d(a,b)
The resulting c is then:
array([ True, True, False, False], dtype=bool)
Upvotes: 1