0

So, I am new to python and currently leading how to program basic functions with it. I have be asked to make a function which spell checks a word against the known correct spelling.

If the word is correct the function returns "correct", if there 2 or less mistakes it returns "almost" and if 3 or more mistakes are present the function returns "wrong". So for example if the function if of the formation spell(correct, guess)
spell('hello', hello') would return 'correct', spell('hello','nello') would return 'almost', and spell('hello','hejje') would return 'wrong'.

My code for this is:

def spell(correct, guess):
    answer=list(guess)
    right=list(correct)
    w=0

    for i in answer and right:
        if answer[i]==right[i]:
            w=w
        else:
            w=w+1
    if w==0:
        print("correct")
    elif w==1 or w==2:
        print("Almost")
    else:
        print("Wrong") 

I trying to define the function by adding up the number of difference between the two lists. But I keep getting the error "list indices must be integers or slices, not str" and I don't know another way of setting up the problem. I want to know the best way to approach coding this so I can try and attempt my code to work.

H.Linkhorn
  • 103
  • 1

2 Answers2

1

Assuming you have something like word1 = 'hello' and word2 = 'nello', then you can do this:

sum(word1[i] != word2[i] for i in range(min(len(word1), len(word2))))

The reason yours isn't working is because of how you are using the for loop:

for i in answer and right:

if answer is ['h', 'e', 'l', 'l', 'o'], then i is going to be each character within that list. As long as what evaluates to right is True and because right is a non-empty list, it will. So i is going to be each character in 'hello', which is why you are getting your error.

EDIT: A simpler version of your for loop:

for i in range(len(answer)):
    if answer[i] != right[i]:
        w = w + 1
Chrispresso
  • 3,660
  • 2
  • 19
  • 31
0

Two issues

1) When you say

for i in answer and right:

the code is only iterating through right. You need to be unambiguous about which list you're iterating through. The solution to this is related to the second issue.

2) Iterating through a list of strings will return strings

Saying

a = ["b", "c", "d"]
for i in a:
    print(a[i])

does not make sense. a[i] means the i^th element of a, but in this case, i is literally the strings you're iterating through. It's equivalent to saying a["b"]

Instead, you should be iterating through the indices of the two lists:

for i in range(len(answer)):
    if answer[i] == right[i]:
        etc...
David
  • 424
  • 3
  • 16