I am attempting to search through two strings looking for matching elements. If the strings have two elements in common that are in different positions, I want to make that element in the 'guess' string a COW. If the strings have two elements in the same position, the element is a BULL.
Here is what I have:
if index(number,i) in guess and not index(guess,i) == index(guess,i):
replace(index(guess,i),'COW')
if index(guess,i) == index(number,i):
replace(index(guess,i),'BULL')
I'm not sure if I'm using index correctly.
First off, you need to be using
index()
andreplace()
as string methods, like Martijn said in a comment.This would be like so:
guess.index(i)
to find the index ofi
in the stringguess
.You might want to check out find() which will do the same as
index()
but won't raise an exception when the substring is not found.Also note that you are seeing if the result of
index()
is in the stringguess
. That is an error, since an integer cannot be in a string!index()
returns an integer!Then consider that you are stating
... and not guess.index(i) == guess.index(i):
(I fixed theindex
code) which makes no sense, since of course they are equal! They are the same thing!Lastly, you are using
replace
incorrectly. From the documentation,replace
takes a string as the first argument - not an index! Try using it like so:guess = guess.replace(i, 'BULL')
. That will changeguess
to have all occurrences ofi
replaced by the string'BULL'
.I wasn't concerned with you actual algorithm here, but just your basic errors.
I wouldn't use the
index()
method. Instead, I would turn the string's elements into a list, then say:This is just how I would do it, but using the way you and William's code may work well also. I am just used to doing it this way, and it may very well be not as efficient as his, but it usually works very well.