Hello Everyone,
I have some questions about the code of the three exercises below:
1, Use for, .split(), and if to create a Statement that will print out words that start with ‘s’:
st = ‘Print only the words that start with s in this sentence’
for word in st.split():
if word[0] == ‘s’: #<-- Here is what I don’t understand.
print(word)
And the output was correct:
start
s
sentence
Why it could work just simply by the code ‘ if word[0] == “s”:‘? I thought word[0] index the first item which is “Print” in st.split().
2, Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.
has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False
def has_33(nums):
for i in range(0, len(nums)-1):
if nums[i:i+2] == [3,3]: # <--- Here is what I don't understand.
return True
return False
And the result was correct
I don’t understand why the part 'i+2 ’ in ‘if nums[i:i+2] == [3,3]’ , why not ‘i+1’ if another way to write this code is ‘if nums[i] == 3 and nums[i+1] == 3:’? Because what it wants id to return True if the array contains a 3 next to a 3 somewhere so why ‘i+2’??
3, PAPER DOLL: Given a string, return a string where for every character in the original there are three characters:
paper_doll(‘Hello’) --> ‘HHHeeellllllooo’
paper_doll(‘Mississippi’) --> ‘MMMiiissssssiiippppppiii’
def paper_doll(text):
result = ‘’ # <-- I’m not clear with this use ‘’
for char in text:
result += char * 3 # <-- I don’t understand here
return result
The result was correct:
‘HHHeeellllllooo’
‘MMMiiissssssiiippppppiii’
#But I don’t understand here:
for char in text:
result += char * 3
I thought ‘char * 3’ will get result like this “hellohellohello”…
Could somebody kindly explain all this to me? Thank you very much.