Chapter “Brute-force algorithms”, exercise 1
Text
Write down the execution steps of linear_search(list(["Coraline", "American Gods", "The Graveyard Book", "Good Omens", "Neverwhere"]), "The Sandman")
, as explained in Listing 7.
Answer
The instructions in the for-each loop used in the function will be executed five times (i.e. for all the items in input_list
), since no item will contain "The Sandman"
as value. Thus, None will be returned.
The various iterations of the for-each loop will be as follows:
- The variable
position
will be set to0
, and the variableitem
will be set to"Coraline"
. The condition defined in the if statement will beFalse
since"Coraline"
is not equal to"The Sandman"
, which is the value to search assigned to the variablevalue_to_search
. Thus, the return instruction under the if block will not be executed. - The variable
position
will be set to1
, and the variableitem
will be set to"American Gods"
. The condition defined in the if statement will beFalse
since"American Gods"
is not equal to"The Sandman"
, which is the value to search assigned to the variablevalue_to_search
. Thus, the return instruction under the if block will not be executed. - The variable
position
will be set to2
, and the variableitem
will be set to"The Graveyard Book"
. The condition defined in the if statement will beFalse
since"The Graveyard Book"
is not equal to"The Sandman"
, which is the value to search assigned to the variablevalue_to_search
. Thus, the return instruction under the if block will not be executed. - The variable
position
will be set to3
, and the variableitem
will be set to"Good Omens"
. The condition defined in the if statement will beFalse
since"Good Omens"
is not equal to"The Sandman"
, which is the value to search assigned to the variablevalue_to_search
. Thus, the return instruction under the if block will not be executed. - The variable
position
will be set to4
, and the variableitem
will be set to"Neverwhere"
. The condition defined in the if statement will beFalse
since"Neverwhere"
is not equal to"The Sandman"
, which is the value to search assigned to the variablevalue_to_search
. Thus, the return instruction under the if block will not be executed.
Since no return instruction will be executed, None
will be implicitly returned by the function.