There are a number of issues to consider:
- Your loop doesn’t iterate over the last character of
string_one
.
# You wrote:
for i in range(len(string_one) - 1):
# It should be:
for i in range(len(string_one)):
You can confirm this by placing a print statement (for debugging purposes) print(string_one[i])
as the first statement of your loop. You will see that your loop doesn’t access the last character of the string.
len(string_one)-1
is the last index of the string, so that’s fine.
But, range
doesn’t include the stop
value i.e.
print(list(range(5)))
# [0, 1, 2, 3, 4]
# The stop value 5 is not included in the range.
Therefore,
for i in range(len(string_one)):
will iterate over the index of the last character without going out of bounds, whereas
for i in range(len(string_one) - 1):
will not iterate over the index of the last character of the string.
I don’t know whether it has been covered in the course at this point, or whether it is a later lesson, but if the index is not necessary and you just want to iterate over the characters of a string, then you could use a loop like:
word = "Hello"
for c in word:
print(c)
-
Since you are using a for
loop to iterate over the range, so the statements i = 0
and i += 1
don’t serve any purpose and should be removed. If you were using a while
loop, then both the statements would be needed for proper initialization and to avoid infinite loop. In a for
loop, the initialization and increment are handled by the loop itself.
-
Your condition is incorrect.
# You wrote:
if string_one[i] in string_two == True:
# It should be:
if string_one[i] in string_two:
You could write the condition as
# Valid syntax
if (string_one[i] in string_two) == True:
#
# but it is better to write as:
if string_one[i] in string_two :
The way that you wrote your condition (since the in
and ==
have equal precedence in Python), your condition would be interpreted as:
if string_one[i] in string_two == True:
#
# is equivalent to:
if (string_one[i] in string_two) and (string_two == True):
Hence, your condition is not evaluating to True
and nothing is being appended to wanted
.
- Also, the exercise mentions
The letters in the returned list should be unique. For example,
common_letters(“banana”, “cream”) should return [‘a’].
So, you will probably want to modify your condition a little to handle this. You may want to have your if
condition also check whether the matched character is already present in the wanted
list or not.