We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
for i in range(len(s)) is an iterator that provides an index for each letter in the string.
s[i] != "SOS"[i%3] is the validation test which results in a True (value = 1) or False (value = 0) - Not equal is used because we are counting mismatches. (i.e. True we have a mismatch)
For each character in the string, using the index we need to test against a single character - so the trick here is to use modulo to get the correct character - "SOS"[0] = "S", "SOS"[1] = "O", "SOS"[2] = "S" the result of index modulo 3 selects the correct comparator for our validation
Finally we return the sum of all of the comparison results
Mars Exploration
You are viewing a single comment's thread. Return to all comments →
Sure. Here is a breakdown of the comprehension:
for i in range(len(s))
is an iterator that provides an index for each letter in the string.s[i] != "SOS"[i%3]
is the validation test which results in aTrue
(value = 1) orFalse
(value = 0) - Not equal is used because we are counting mismatches. (i.e. True we have a mismatch)For each character in the string, using the index we need to test against a single character - so the trick here is to use modulo to get the correct character -
"SOS"[0] = "S", "SOS"[1] = "O", "SOS"[2] = "S"
the result of index modulo 3 selects the correct comparator for our validationFinally we return the sum of all of the comparison results