In: Computer Science
What I have bolded is what is wrong with this function and cant figure out what needs to bee done to get the second position of this comma?Need help building this function to do what the specifications say to do
import introcs
def second_in_list(s):
"""
Returns: the second item in comma-separated list
The final result should not have any whitespace around the
edges.
Example: second_in_list('apple, banana, orange') returns
'banana'
Example: second_in_list(' do , re , me , fa ') returns 're'
Example: second_in_list('z,y,x,w') returns 'y'
Parameter s: The list of items
Precondition: s is a string of at least three items separated by
commas.
"""
slice = s
first = introcs.find_str(slice,',') #find position of my first
comma
print(first)
second = introcs.find_str(slice,',',5,-1) #need to
find the position after the first comma
print(second)
#need to useee the positions of my commas to slice the desired
output (ie slice[first:seond])
slice2 = slice[first+1:second]
result = introcs.strip(slice2)
return result
return result
If I understand correctly from your code, you were trying to find second element in the list('apple, banana, orange'). The documentation of introcs.find_str says it has the following parameters:
text (str
) – The string to
search
sub (str
) – The substring to
search for
start (int
) – The start of the
search range
end (int
) – The end of the search
range
Now, looking from the function defination, the third parameter is the start. According to your code, the third parameter for the second introcs.find_str function is 5 i.e. the value of first. This is where you are making the mistake. The start value should be first + 1 instead of first because if you initialize the start parameter as first, it will also include the first comma in the resultant substring(the substring that you are searching the second time).
Below I have corrected your code in Python and also attached
sample outputs.
Please upvote if you like my work.
Code screenshot:
Code to copy:
import introcs
def second_in_list(s):
slice = s
first = introcs.find_str(slice,',') #find position of my first comma
print(first)
second = introcs.find_str(slice,',',first+1,-1) #need to find the position after the first comma
print(second)
#need to useee the positions of my commas to slice the desired output (ie slice[first:seond])
slice2 = slice[first+1:second]
result = introcs.strip(slice2)
return result
Inputs and outputs: