167k views
5 votes
The function below takes two arguments, a list full of strings and an integer threshold.

Fix the function such that it returns a new list full of all the strings that are shorter than the threshold.
student.py 2
1 - def filter_strings_by_threshold(string_list, threshold):
2 - nsl = []
3- for s in string_list:
4- if len(s) < threshold:
5 returns
6 return ns11

User Grabofus
by
7.4k points

1 Answer

6 votes

Final answer:

The given code snippet is a Python function that filters a list of strings based on a given threshold value and returns a new list of shorter strings.

Step-by-step explanation:

The given code snippet is a Python function that takes two arguments: a list full of strings and an integer threshold. The function aims to return a new list containing all the strings that are shorter than the threshold.

To fix the code, we need to correct the following mistakes:

  1. Add an empty list called 'ns1' to store the qualifying strings.
  2. Iterate over each string in the 'string_list' using a for loop and check if its length is less than the 'threshold'.
  3. If the length is less than the threshold, add the string to the 'ns1' list.
  4. Finally, return the 'ns1' list.

Here is the corrected code:

def filter_strings_by_threshold(string_list, threshold):
ns1 = []
for s in string_list:
if len(s) < threshold:
ns1.append(s)
return ns1

User LostMohican
by
7.9k points