Write a function called starts_with(prefix, wordlist) that takes as inputs a string prefix and a list of strings wordlist, and that uses a list comprehension to return a list consisting of all words from wordlist that begin with prefix. For example:

>>> starts_with('fun', ['functions', 'are', 'really', 'fun!'])
result: ['functions', 'fun!']

>>> starts_with('on', ['only', 'functions', 'on', 'the', 'brain'])
result: ['only', 'on'] # note that 'functions' is *not* included

>>> names = ['Alex', 'Adlai', 'Alison', 'Amalia', 'Anbita']
>>> starts_with('A', names)
result: ['Alex', 'Adlai', 'Alison', 'Amalia', 'Anbita']

>>> starts_with('Al', names)
result: ['Alex', 'Alison']

>>> starts_with('D', names)
result: []
Hints:

Your list comprehension will need an if clause.

Make sure that you only include words that start with the specified prefix. For instance, in the second example above, the string 'functions' is not included in the return value, because the string 'on' is in the middle of 'functions', rather than at the start. As a result, you won’t be able to use the in operator to test for the presence of the prefix in a word.

Respuesta :

Answer:

Hi there! The question can easily be implemented by iterating through the array list an using the "startswith()" function of the String class. Please find explanation below.

Explanation:

We can write the code as below into a file called starts_with.py and run it from the command line. Sample input is also provided with results.

starts_with.py

import sys;

def starts_with(prefix, wordlist):

   for e in wordlist:

       if e.lower().startswith(prefix.lower()):

           starts_with_array.append(e);

starts_with_array = [];

prefix = input("Enter prefix: ");

wordlist = input("Enter word list: ");

wordlist = wordlist.split(',');

starts_with(prefix, wordlist);

print(starts_with_array);

Usage with Result

> starts_with.py

> Enter prefix: Fun

> Enter word list: Funtastic,Fun,Test,No

> ['Funtastic', 'Fun']

The function is an illustration of loops and conditional statements.

Loops are used to perform repetitive operations, while conditional statements are statements whose executions depend on the truth values of the conditions.

The function, where comments are used to explain each line is as follows:

#This defines the function

def starts_with(prefix,wordList):

   #This initializes the output list

   result = []

   #This iterates through every string on the list

   for word in wordList:

       #This checks if each word begins with the prefix

       if (word.startswith(prefix)):

           #If yes, the word is appended to the output list

           result.append(word)

   #This prints the output list

   print(result)

At the end of the program, a list of words that begin with prefix is printed.

Read more about similar programs at:

https://brainly.com/question/6615418