CSCI 1100 - Test 2 Overview and Practice Questions
Important Logistical Instructions:
- Test 2 will be held Thursday, March 14, 2024.
- Most students will take the exam from 6:00 - 7:30 pm. Students who provided us with an accommodation letter indicating the need for extra time or a quiet location will be given a separate room and may be allowed to continue past 7:30.
- Room assignments will be posted on Submitty by the Wednesday night before the exam, March 13th.
- Students MUST:
- Go to their assigned rooms.
- Bring their IDs to the exam.
- Sit in the correct section.
- Put away all calculators, phones, etc. and take off/out all headphones and earbuds
Failing to do one of these may result in a 20 point penalty on the exam score. Failure to do all can cost up to 80 points.
- You cannot leave the exam room (not even for a bathroom break) until you hand over your exam.
- Similar to exam 1, a one-page crib-sheet is allowed during the test.
Overview
Exam Coverage
The primary coverage for this exam includes Lectures 7-13, Labs 3-6, and Homework 2-5. Material from tuples and modules are also part of this test. However, images will not be covered.
Important Topics
- Lists and tuples: Be comfortable with list functions (append, insert, remove, concatenation, replication, and slicing) and understand the differences between tuples, strings, and lists.
- Control structures: Study the use of if statements, while and for loops, ranges, splitting, and slicing.
- Basic list operations: Learn to compare items from two separate lists, find specific items in a list, find the index of a specific item in a list (min, max, last value with some property), and add up values in a list.
- Functions over lists: Write functions to check if a list contains a specific type of item (e.g., negative, 0, divisible by 3) and return True or False accordingly.
- Booleans and comparisons: Know booleans, comparisons, and the boolean functions and, or, and not. Be able to generate truth tables for boolean expressions.
- File operations: Know how to read data from files and perform other file operations.
Grids (List of Lists)
Get comfortable working with grids (list of lists). Know how to print a grid using nested loops and practice checking neighbors of a given element in a list of lists. Review these concepts by re-reading/re-writing your solutions for homework 5.
Previous Material
While the exam will focus on the material above, questions may be asked about any material from previous labs, lectures, and homeworks. Make sure you understand the difference between printing a value in a function, returning a value from a function, or both printing and returning.
Exam Rules
No calculators, textbooks, class notes, smart watches, or electronics of any kind are allowed. However, you may bring a one-page, double-sided, 8.5" x 11" “crib sheet” that you can prepare as you wish, even in groups. Each student must have their own copy during the test and turn it in with the exam.
Sample Questions and Solutions
Many sample questions, more than will be on the test, are provided. Solutions to most of the problems will be posted online in the Course Resources section of Submitty, except for problems involving output from Python, which you should test yourself. Your solution to any question requiring Python code will be at most 10-15 lines long, and may be much shorter. The test questions will be closely related to these practice problems and problems from the homework, labs, and lecture exercises.
Additional Tips
- Syntax will be less important on this test than on the previous test, but do not ignore it entirely.
- Learn to read and follow code to develop your debugging skills and understanding of
Questions
Compare Date
Write a Python function called compare date that takes as arguments two lists of two integers each. Each list contains a month and a year, in that order. The function should return -1 if the first month and year are earlier than the second month and year, 0 if they are the same, and 1 if the first month and year are later than the second. Your code should work for any legal input for month and year. Example calls and expected output are shown below:
1 2 3 4 5 6
>>> compare_date( [10,1995], [8,1995] ) 1 >>> compare_date( [5,2010], [5,2010] ) 0 >>> compare_date( [10,1993], [8,1998] ) -1
Answer of This Question
Here’s a Python function that compares two dates given as lists of month and year and returns -1, 0, or 1 based on their order:
|
|
Explanation:
-
The function
compare_date
takes two arguments,date1
anddate2
, which are lists containing the month and year of each date. -
We unpack the month and year from each date list into separate variables:
month1
,year1
,month2
, andyear2
. -
We first compare the years:
- If
year1
is less thanyear2
, we return -1 since the first date is earlier. - If
year1
is greater thanyear2
, we return 1 since the first date is later. - If
year1
is equal toyear2
, we move on to compare the months.
- If
-
If the years are the same, we compare the months:
- If
month1
is less thanmonth2
, we return -1 since the first date is earlier. - If
month1
is greater thanmonth2
, we return 1 since the first date is later. - If
month1
is equal tomonth2
, we return 0 since the dates are the same.
- If
The function correctly handles any legal input for month and year. It compares the years first, and if they are the same, it compares the months to determine the order of the dates.
You can test the function with the provided example calls:
|
|
The function will return the expected output for each example call.
Highest Two Values
Assume v is a list containing numbers. Write Python code to find and print the highest two values in v. If the list contains only one number, print only that number. If the list is empty, print nothing. For example, if we assigned
1
v = [ 7, 3, 1, 5, 10, 6 ]
then the output of your code should be something like
1
7 10
If we are given that
1
v = [ 7 ]
then the output of your code should be
1
7
Answer of This Question
Here’s the Python code to find and print the highest two values in a list v
:
|
|
Explanation:
-
We start by checking the length of the list
v
using thelen()
function. -
If the length of
v
is greater than or equal to 2, it means there are at least two elements in the list. In this case:- We find the highest value in the list using the
max()
function and store it in the variablehighest
. - We remove the highest value from the list using the
remove()
method. This is done to find the second highest value. - We find the second highest value in the updated list using
max()
again and store it in the variablesecond_highest
. - Finally, we print the
second_highest
andhighest
values separated by a space.
- We find the highest value in the list using the
-
If the length of
v
is equal to 1, it means there is only one element in the list. In this case:- We simply print the only element in the list, which is accessed using
v[0]
.
- We simply print the only element in the list, which is accessed using
-
If the length of
v
is 0 (i.e., the list is empty), the code will not execute any of the conditions, and nothing will be printed.
Examples:
-
If
v = [7, 3, 1, 5, 10, 6]
, the output will be:1
7 10
-
If
v = [7]
, the output will be:1
7
-
If
v = []
(an empty list), no output will be generated.
This code efficiently finds and prints the highest two values in the list, handles the case when there is only one element, and does nothing if the list is empty.
Italian Restaurants
Consider a simplified version of the lab Yelp data, where just the name of the restaurant, the type of restaurant, and the ratings are provided. Assume these values have already been read into a list of lists of the form below:
1 2 3 4 5
restaurants = [ [ 'Acme', 'Italian', 2, 4, 3, 5], [ 'Flintstone', 'Steak', 5, 2, 4, 3, 3, 4], [ 'Bella Troy', 'Italian', 1, 4, 5] ]
Write a segment of Python code that prints all Italian restaurants in the
restaurants
list that have no ratings of value 1 and at least one rating of value 5. In the above example,Acme
would be printed in the output, butFlintstone
andBella Troy
would not.Flintstone
is not Italian andBella Troy
has a 1 rating. Your code should work for any legal version ofrestaurants
.
Answer of This Question
Here’s the Python code that prints all Italian restaurants in the restaurants
list that have no ratings of value 1 and at least one rating of value 5:
|
|
Explanation:
-
We start by iterating over each restaurant in the
restaurants
list using afor
loop. Each restaurant is represented as a sublist within therestaurants
list. -
Inside the loop, we check three conditions using an
if
statement:restaurant[1] == 'Italian'
: This condition checks if the second element of the current restaurant sublist is equal to the string ‘Italian’. This ensures that we are only considering Italian restaurants.1 not in restaurant[2:]
: This condition checks if the value 1 is not present in the ratings of the current restaurant. We use slicing (restaurant[2:]
) to consider only the ratings, which start from the third element of the sublist.5 in restaurant[2:]
: This condition checks if the value 5 is present in the ratings of the current restaurant. Again, we use slicing to consider only the ratings.
-
If all three conditions are satisfied for a restaurant, it means that the restaurant is Italian, has no ratings of value 1, and has at least one rating of value 5. In this case, we print the name of the restaurant, which is the first element of the restaurant sublist (
restaurant[0]
). -
The loop continues to the next restaurant in the
restaurants
list until all restaurants have been checked.
Using the example restaurants
list provided:
|
|
The output of the code will be:
|
|
Only ‘Acme’ is printed because it is an Italian restaurant with no ratings of value 1 and at least one rating of value 5. ‘Flintstone’ is not Italian, and ‘Bella Troy’ has a rating of value 1, so they are not printed.
This code will work for any valid restaurants
list that follows the specified format.
High Average Rating Restaurants
Continuing with the Yelp data, assume that you have the code
1 2 3 4
in_file = open('yelp.txt') for line in in_file: p_line = parse_line(line) print(p_line)
and that the
parse_line
function will return a list that looks like
1
["Meka's Lounge", 42.74, -73.69, "Bars", [5, 2, 4, 4, 3, 4, 5], 3.857 ]
where the last entry in the list is the average rating. Modify the for loop above to create a list called
high
that stores the names of all restaurants that have an average rating of at least 4.0. You do not have to printhigh
.
Answer of This Question
To create a list called high
that stores the names of all restaurants with an average rating of at least 4.0, you can modify the for
loop as follows:
|
|
Explanation:
-
Before the
for
loop, we initialize an empty list calledhigh
to store the names of the restaurants with high average ratings. -
Inside the
for
loop, we parse each line of the file using theparse_line
function, which returns a listp_line
with the restaurant’s information. -
We check if the last element of
p_line
(i.e.,p_line[-1]
), which represents the average rating, is greater than or equal to 4.0 using the conditionif p_line[-1] >= 4.0
. -
If the condition is true, it means the restaurant has an average rating of at least 4.0. In this case, we append the name of the restaurant, which is the first element of
p_line
(i.e.,p_line[0]
), to thehigh
list usinghigh.append(p_line[0])
. -
The loop continues to the next line in the file until all lines have been processed.
After the loop finishes, the high
list will contain the names of all restaurants with an average rating of at least 4.0.
For example, if the yelp.txt
file contains the following lines:
|
|
After running the modified code, the high
list will contain:
|
|
These are the names of the restaurants with an average rating of at least 4.0.
Note that we don’t print the high
list in the code as per the requirement. The list will be available for further use if needed.
Chess Score
In the game of chess you can often estimate how well you are doing by adding the values of the pieces you have captured. The pieces are Pawns, Bishops, Knights, Rooks and Queens. Their values are
1 2 3 4 5
P - (P)awn, value = 1 B - (B)ishop, value = 3 K - (K)night, value = 3 R - (R)ook, value = 5 Q - (Q)ueen, value = 9
Write a Python function called
chess_score
that takes a single string as an argument and returns the combined values represented by the pieces in the string. You may assume that only ‘P’, ‘B’, ‘K’, ‘R’, and ‘Q’ appear in the string. You may not use any if statements and you may not use any loops. As an example,
1
print(chess_score('BQBP'))
should output the value 16 because there are 2 Bishops (3 points each), 1 Queen (9 points each), and 1 Pawn (1 point each).
Answer of This Question
Here’s a Python function chess_score
that calculates the combined values of the chess pieces represented by a string without using any if
statements or loops:
|
|
Explanation:
-
The function
chess_score
takes a single stringpieces
as an argument, which represents the captured chess pieces. -
To calculate the score, we use the
count()
method of the string to count the occurrences of each piece and multiply it by its corresponding value:pieces.count('P')
: Counts the number of Pawns (‘P’) in the string and multiplies it by 1 (the value of a Pawn).pieces.count('B') * 3
: Counts the number of Bishops (‘B’) in the string and multiplies it by 3 (the value of a Bishop).pieces.count('K') * 3
: Counts the number of Knights (‘K’) in the string and multiplies it by 3 (the value of a Knight).pieces.count('R') * 5
: Counts the number of Rooks (‘R’) in the string and multiplies it by 5 (the value of a Rook).pieces.count('Q') * 9
: Counts the number of Queens (‘Q’) in the string and multiplies it by 9 (the value of a Queen).
-
The function returns the sum of all the calculated values, which represents the total score of the captured pieces.
Example usage:
|
|
Output:
|
|
Explanation:
- The string ‘BQBP’ contains 2 Bishops (‘B’), 1 Queen (‘Q’), and 1 Pawn (‘P’).
- The score is calculated as follows:
- 2 Bishops * 3 points each = 6 points
- 1 Queen * 9 points each = 9 points
- 1 Pawn * 1 point each = 1 point
- The total score is 6 + 9 + 1 = 16.
This function calculates the chess score based on the captured pieces represented by the input string without using any if
statements or loops. It utilizes the count()
method to count the occurrences of each piece and multiplies them by their respective values to obtain the total score.
Sum Integers from File
You are given a file that contains, on each line of input, three integers separated by commas. Write a Python program that sums all of the first integers, the second integers, and the third integers, outputting the resulting sums all on one line, separated by commas. As a simple example, if the input is
1 2 3 4
2, 5,7 3, 6, 10 1, 2, -3 2, 4, 1
Then the output should be
1
8, 17, 15
Answer of This Question
Here’s the Python program that reads integers from a file, sums them based on their positions, and outputs the resulting sums:
|
|
Explanation:
-
We start by opening the file named ‘input.txt’ for reading using the
with
statement. This ensures that the file is properly closed after we’re done reading from it. -
We initialize three variables
sum1
,sum2
, andsum3
to store the sums of the first, second, and third integers, respectively. -
We use a
for
loop to read each line from the file. Thefile
object is iterable, so we can directly iterate over its lines. -
For each line, we use the
strip()
method to remove any leading or trailing whitespace, and then we use thesplit(',')
method to split the line into individual integers based on the comma separator. This gives us a list of strings representing the integers. -
We convert each integer string to an actual integer using the
int()
function and add it to the respective sum variable (sum1
,sum2
, orsum3
) based on its position in the line. -
After processing all the lines, we have the final sums stored in
sum1
,sum2
, andsum3
. -
Finally, we use the
print()
function to output the resulting sums separated by commas. We use an f-string to format the output, where{sum1}
,{sum2}
, and{sum3}
are placeholders for the actual sum values.
Make sure to save the input data in a file named ‘input.txt’ in the same directory as the Python script. When you run the script, it will read the integers from the file, calculate the sums, and output the resulting sums separated by commas.
Generate Ranges
Write a single line of Python code to generate the following ranges
(a) [100, 99, 98, . . . , 0]
(b) [55, 53, 51, . . . ,−1]
(c) [3, 5, 7, 9, . . . , 29]
(d) [−95,−90,−85, . . . , 85, 90]Now do it using a loop. For the loop, you can assume the list will be in the variable
L
at the end.
Answer of This Question
Single line of Python code to generate the ranges:
(a) list(range(100, -1, -1))
(b) list(range(55, -2, -2))
(c) list(range(3, 30, 2))
(d) list(range(-95, 91, 5))
Using a loop to generate the ranges:
(a)
|
|
(b)
|
|
(c)
|
|
(d)
|
|
Explanation:
-
Single line of Python code:
- We use the
range()
function to generate the desired range of numbers. - The
range()
function takes three arguments: start, stop, and step.- start: The starting number of the range (inclusive).
- stop: The ending number of the range (exclusive).
- step: The difference between each number in the range.
- We wrap the
range()
function with thelist()
function to convert the range object into a list.
- We use the
-
Using a loop:
- We initialize an empty list
L
to store the numbers. - We use a
for
loop to iterate over the desired range of numbers. - Inside the loop, we use the
append()
method to add each number to the listL
. - The loop parameters are the same as the
range()
function arguments:- start: The starting number of the range (inclusive).
- stop: The ending number of the range (exclusive).
- step: The difference between each number in the range.
- We initialize an empty list
Both approaches generate the same ranges of numbers. The single line of code is more concise, while the loop approach allows for more flexibility and customization if needed.
Sum Until Negative
Write a while loop to add all of the numbers in a list
v
until it reaches a negative number or until it reaches the end of the list. Store the sum in the variableresult
. Your code should work for any version ofv
containing only numbers. For example, the value ofresult
should be 25 after the loop for both of the following lists:
1 2
v = [ 10, 12, 3, -5, 5, 6 ] v = [ 0, 10, 3, 6, 5, 1 ]
Answer of This Question
Here’s the Python code that uses a while loop to add all the numbers in a list v
until it reaches a negative number or the end of the list:
|
|
Explanation:
-
We initialize two variables:
i
: It serves as the index variable to keep track of the current position in the listv
. It starts from 0, representing the first element of the list.result
: It stores the sum of the numbers. It is initialized to 0.
-
We start a while loop with two conditions:
i < len(v)
: This condition checks if the indexi
is within the bounds of the listv
. It ensures that we don’t go beyond the last element of the list.v[i] >= 0
: This condition checks if the current element at indexi
is non-negative. It ensures that we stop adding numbers when we encounter a negative number.
-
Inside the loop:
- We add the current element at index
i
to theresult
variable using the+=
operator. This accumulates the sum of the numbers. - We increment the index
i
by 1 usingi += 1
to move to the next element in the list.
- We add the current element at index
-
The loop continues until either of the conditions becomes false:
- If
i
becomes equal to or greater thanlen(v)
, it means we have reached the end of the list, and the loop terminates. - If the current element at index
i
is negative (v[i] < 0
), the loop terminates.
- If
-
After the loop ends, the
result
variable will contain the sum of all the numbers in the listv
until a negative number is encountered or the end of the list is reached.
Let’s test the code with the given examples:
Example 1:
|
|
After the loop, result
will be 25 because the loop stops when it reaches the negative number -5.
Example 2:
|
|
After the loop, result
will also be 25 because the loop adds all the numbers until it reaches the end of the list.
The code works correctly for any list v
containing only numbers, and it stops adding numbers when it encounters a negative number or reaches the end of the list.
Positive Values in Increasing Order
Write Python code that takes a list of numbers,
v
, and outputs the positive values that are inv
in increasing order, one value per line. If there are no positive values, then the output should be the string ‘None’. You may assume there is at least one value in the list. As an example,
1
v = [ 17, -5, 15, -3, 12, -5, 0, 12, 22, -1 ]
Then the output of your code should be
1 2 3 4 5
12 12 15 17 22
As a second example, if
1
v = [ -17, -5, -15, -3, -12, -5, 0, -12, -22, -1 ]
then then output should be just
1
None
Answer of This Question
Here’s the Python code that takes a list of numbers, v
, and outputs the positive values in increasing order, one value per line, or ‘None’ if there are no positive values:
|
|
Explanation:
-
We use the
filter()
function to create an iterator that contains only the positive values from the listv
. Thelambda
functionlambda x: x > 0
is used as the filtering condition, which returnsTrue
for values greater than 0 (positive values). -
We pass the iterator returned by
filter()
to thesorted()
function, which sorts the positive values in ascending order. The result is stored in thepositive_values
list. -
We use an
if-else
statement to check if there are any positive values in thepositive_values
list:- If
positive_values
is not empty (evaluates toTrue
), it means there are positive values in the list.- We use a
for
loop to iterate over each value inpositive_values
. - Inside the loop, we use the
print()
function to output each positive value on a separate line.
- We use a
- If
positive_values
is empty (evaluates toFalse
), it means there are no positive values in the list.- We use the
print()
function to output the string ‘None’.
- We use the
- If
Let’s test the code with the given examples:
Example 1:
|
|
Output:
|
|
Example 2:
|
|
Output:
|
|
The code correctly outputs the positive values in increasing order, one value per line, for the first example. For the second example, where there are no positive values, it outputs ‘None’.
Note: The code assumes that there is at least one value in the list v
, as mentioned in the problem statement.
List Operations Output
What is the output of the following operations:
1 2 3 4 5 6 7 8 9 10
>>> mylist = [1,4,8,12,6] >>> x = mylist.sort() >>> print(x) >>> mylist = [1,4,8,12,6] >>> slice1 = mylist[2:4] >>> slice1[0] = 20 >>> print(slice1) >>> print(mylist)
Answer of This Question
The output of the given operations will be as follows:
Operation 1:
|
|
Output:
|
|
Explanation:
- The
sort()
method sorts the listmylist
in place, modifying the original list. - The
sort()
method returnsNone
, not the sorted list. - When you assign the result of
mylist.sort()
tox
,x
becomesNone
. - Printing
x
outputsNone
.
Operation 2:
|
|
Output:
|
|
Explanation:
mylist[2:4]
creates a new listslice1
containing elements from index 2 to 3 (exclusive) ofmylist
.slice1
is a separate list frommylist
, and modifyingslice1
does not affectmylist
.slice1[0] = 20
assigns the value 20 to the first element ofslice1
.- Printing
slice1
outputs[20, 12]
.
Operation 3:
|
|
Output:
|
|
Explanation:
mylist
remains unchanged from its original state[1, 4, 8, 12, 6]
.- The modifications made to
slice1
in Operation 2 do not affectmylist
. - Printing
mylist
outputs[1, 4, 8, 12, 6]
.
In summary:
- Operation 1 outputs
None
becausesort()
modifies the list in place and returnsNone
. - Operation 2 outputs
[20, 12]
becauseslice1
is a separate list, and modifying it does not affectmylist
. - Operation 3 outputs
[1, 4, 8, 12, 6]
becausemylist
remains unchanged from its original state.
Function Output
What is the output of the following program?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
def spam(a1,b1,a2,b2): if (a1 == a2) and (b1 > b2): return 1 else: return 0 def egg(a1,b1,a2,b2): if (a1 > a2) and (b1 == b2): return 0 else: return 1 a1 = 3 b1 = 4 a2 = 6 b2 = 4 print(spam(a2, b2, a1, b1)) print(egg(a1, b1, a2, b2)) c = spam(a1, b2, a2, b1) print(c) c += egg(a1, b2, a2, b1) print(c)
Answer of This Question
The output of the given program will be:
|
|
Explanation:
-
The program defines two functions:
spam()
andegg()
. -
The
spam()
function takes four parameters (a1, b1, a2, b2) and returns 1 if a1 is equal to a2 and b1 is greater than b2. Otherwise, it returns 0. -
The
egg()
function takes four parameters (a1, b1, a2, b2) and returns 0 if a1 is greater than a2 and b1 is equal to b2. Otherwise, it returns 1. -
The program initializes four variables: a1 = 3, b1 = 4, a2 = 6, and b2 = 4.
-
The first
print()
statement calls thespam()
function with arguments (a2, b2, a1, b1), which are (6, 4, 3, 4). Since a2 (6) is not equal to a1 (3), the function returns 0. Therefore, the first output is 0. -
The second
print()
statement calls theegg()
function with arguments (a1, b1, a2, b2), which are (3, 4, 6, 4). Since a1 (3) is not greater than a2 (6), the function returns 1. Therefore, the second output is 1. -
The variable
c
is assigned the result of calling thespam()
function with arguments (a1, b2, a2, b1), which are (3, 4, 6, 4). Since a1 (3) is not equal to a2 (6), the function returns 0. Therefore,c
is assigned the value 0. -
The third
print()
statement outputs the value ofc
, which is 0. -
The line
c += egg(a1, b2, a2, b1)
is equivalent toc = c + egg(a1, b2, a2, b1)
. It calls theegg()
function with arguments (a1, b2, a2, b1), which are (3, 4, 6, 4). Since a1 (3) is not greater than a2 (6), the function returns 1. The returned value is added to the current value ofc
, which is 0. Therefore,c
becomes 1. -
The fourth
print()
statement outputs the updated value ofc
, which is 1.
In summary, the program outputs:
- 0 (result of
spam(a2, b2, a1, b1)
) - 1 (result of
egg(a1, b1, a2, b2)
) - 0 (value of
c
after callingspam(a1, b2, a2, b1)
) - 1 (value of
c
after adding the result ofegg(a1, b2, a2, b1)
to the previous value ofc
)
Copy Odd Lines
Write a function called
copy_half
that takes the name of two files as arguments. The function should copy the first, third, fifth, etc. lines (i.e. odd lines only) from the first file to the second file. For example, if the file names are ‘in.txt’ and ‘out.txt’ and if ‘in.txt’ contains
1 2 3 4 5
starting line not this line middle line is here skip this line too I like this line
then after the call
1
copy_half( 'in.txt', 'out.txt' )
the file ‘out.txt’ should contain
1 2 3
starting line middle line is here I like this line
Answer of This Question
Here’s the solution to the problem:
|
|
Explanation:
-
The function
copy_half
takes two arguments:file1
(the input file) andfile2
(the output file). -
We open both files using the
with
statement, which ensures that the files are properly closed after we’re done with them. We openfile1
in read mode (‘r’) andfile2
in write mode (‘w’). -
We read all the lines from the input file using
readlines()
and store them in thelines
list. -
We start a
for
loop that iterates over the indices oflines
with a step of 2 usingrange(0, len(lines), 2)
. This ensures that we process only the odd-indexed lines (1st, 3rd, 5th, etc.). -
Inside the loop, we write each odd-indexed line to the output file using
output_file.write(lines[i])
. This copies the line from the input file to the output file. -
The loop continues until all the odd-indexed lines have been processed and written to the output file.
-
After the loop finishes, the
with
statement automatically closes both files.
So, when you call the function copy_half('in.txt', 'out.txt')
, it will read the contents of ‘in.txt’, copy the odd-indexed lines (1st, 3rd, 5th, etc.), and write them to ‘out.txt’. The resulting ‘out.txt’ file will contain only the odd lines from ‘in.txt’.
Separate Positive and Negative Values
Write a segment of code that reads integers from a file called
test2.txt
and stores the positive values in one list, the negative values in a second list, and skips blank lines and zeros. The order of the values in each list should match the order of the input. Each line of input will contain either spaces or spaces and an integer. For example, iftest2.txt
contains
1 2 3 4 5
11 -3 5 0
Then after your code, the list
P
should be[ 11, 5 ]
and the listN
should be[ -3 ]
.
Answer of This Question
Here’s the code segment that reads integers from the file test2.txt
, stores the positive values in a list P
, stores the negative values in a list N
, and skips blank lines and zeros:
|
|
Explanation:
-
We initialize two empty lists:
P
to store the positive values andN
to store the negative values. -
We open the file
test2.txt
in read mode using thewith
statement, which ensures that the file is properly closed after we’re done with it. -
We start a
for
loop that iterates over each line in the file usingfor line in file:
. -
For each line, we use
line.strip()
to remove any leading or trailing whitespace characters (including newline characters). -
We check if the stripped line is not empty using
if line:
. This condition skips blank lines. -
If the line is not empty, we convert it to an integer using
int(line)
and store it in the variablenum
. -
We then check the value of
num
:- If
num
is greater than 0, we append it to the listP
usingP.append(num)
. - If
num
is less than 0, we append it to the listN
usingN.append(num)
. - If
num
is equal to 0, we skip it and move on to the next line.
- If
-
The loop continues until all the lines in the file have been processed.
-
After the loop finishes, the
with
statement automatically closes the file.
So, after running this code segment, the list P
will contain the positive values from the file test2.txt
in the order they appeared, and the list N
will contain the negative values in the order they appeared. Blank lines and zeros will be skipped.
For the given example, if test2.txt
contains:
|
|
Then the resulting lists will be:
P = [11, 5]
N = [-3]
Code Output 1
Give the output of each of the following
(a)
1 2 3 4 5 6 7 8
i = 4 L = [ 0, 12, 3, 5, 2, -1 ] while 0 <= i and i < len(L): if L[i] < 0: break else: i = L[i] print(i, L[i])
(b)
1 2 3 4 5 6 7 8 9
tough = 2 for i in range(2): s = 1 for j in range(i, tough): s += tough print(s) print(tough) tough = s print(tough)
Answer of This Question
(a) Output:
|
|
Explanation:
- The variable
i
is initialized to 4. - The list
L
is defined as[0, 12, 3, 5, 2, -1]
. - The
while
loop starts with the condition0 <= i and i < len(L)
, which is true sincei
is 4 and the length ofL
is 6. - Inside the loop, the condition
L[i] < 0
is checked. SinceL[4]
is 2, which is not less than 0, theelse
block is executed. - In the
else
block,i
is assigned the value ofL[i]
, which isL[4] = 2
. So,i
becomes 2. - The loop continues with the updated value of
i
, and the condition0 <= i and i < len(L)
is still true. - The condition
L[i] < 0
is checked again. SinceL[2]
is 3, which is not less than 0, theelse
block is executed. - In the
else
block,i
is assigned the value ofL[i]
, which isL[2] = 3
. So,i
becomes 3. - The loop continues with the updated value of
i
, and the condition0 <= i and i < len(L)
is still true. - The condition
L[i] < 0
is checked again. SinceL[3]
is 5, which is not less than 0, theelse
block is executed. - In the
else
block,i
is assigned the value ofL[i]
, which isL[3] = 5
. So,i
becomes 5. - The loop continues with the updated value of
i
, but the condition0 <= i and i < len(L)
is now false sincei
is 5, which is not less than the length ofL
. - The loop terminates, and the values of
i
andL[i]
are printed. At this point,i
is 5 andL[5]
is -1. - Therefore, the output is
2 3
.
(b) Output:
|
|
Explanation:
- The variable
tough
is initialized to 2. - The outer
for
loop starts withi
ranging from 0 to 1 (two iterations). - In the first iteration (
i = 0
):s
is initialized to 1.- The inner
for
loop starts withj
ranging from 0 to 1 (two iterations). - In each iteration of the inner loop,
s
is incremented bytough
, which is 2. So,s
becomes 3. - After the inner loop,
s
is printed, which is 3. tough
is printed, which is 2.tough
is updated with the value ofs
, sotough
becomes 3.- The updated value of
tough
is printed, which is 3.
- In the second iteration (
i = 1
):s
is initialized to 1.- The inner
for
loop starts withj
ranging from 1 to 2 (two iterations). - In each iteration of the inner loop,
s
is incremented bytough
, which is now 3. So,s
becomes 7. - After the inner loop,
s
is printed, which is 7. tough
is printed, which is 3.tough
is updated with the value ofs
, sotough
becomes 7.- The updated value of
tough
is printed, which is 7.
- The outer loop terminates, and the program ends.
- Therefore, the output is:
1 2 3 4 5 6
3 2 3 7 3 7
Code Output 2
Please show the output from the following code?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
def get_min(v): v.sort() return v[0] def get_max(v): x = max(v) return x v = [ 14, 19, 4, 5, 12, 8 ] if len(v) > 10 and get_min(v) > 6: print("Hello") print(v[0]) print(v[4]) else: print("So long") print(v[0]) print(v[-1]) if len(v) < 10 or get_max(v): print(get_max(v)) print(v[0]) print(get_min(v)) print(v[0])
Answer of This Question
The output from the given code will be:
|
|
Explanation:
- The list
v
is initialized with the values[14, 19, 4, 5, 12, 8]
. - The
if
conditionlen(v) > 10 and get_min(v) > 6
is evaluated:len(v)
is 6, which is not greater than 10.- The function
get_min(v)
is called, which sorts the listv
in ascending order and returns the first element, which is 4. However, 4 is not greater than 6. - Since both conditions are not satisfied, the
else
block is executed.
- Inside the
else
block:- The string “So long” is printed.
v[0]
, which is 4, is printed.v[-1]
, which is 19, is printed.
- The next
if
conditionlen(v) < 10 or get_max(v)
is evaluated:len(v)
is 6, which is less than 10, so the condition is true.- The function
get_max(v)
is called, which returns the maximum value in the listv
, which is 19. Since 19 is a truthy value, the condition is also true. - Since either of the conditions is true, the block inside the
if
statement is executed.
- Inside the
if
block:get_max(v)
, which is 19, is printed.v[0]
, which is 4, is printed.get_min(v)
, which is 4 (since the listv
is already sorted from the previous call toget_min()
), is printed.v[0]
, which is 4, is printed again.
- The program ends.
Therefore, the output will be:
|
|
Elephant Steps
Show the output from the following code:
1 2 3 4 5 6 7 8 9 10 11 12
def elephant(height): time_step = 1 steps = 0 while steps < height: steps += time_step steps -= time_step//3 time_step += 1 print("{}, {}".format(time_step, steps)) elephant(0) elephant(5) elephant(6)
Answer of This Question
The output from the given code will be:
|
|
Explanation:
- The function
elephant(height)
is defined, which takes an integerheight
as input. - Inside the function:
- The variable
time_step
is initialized to 1. - The variable
steps
is initialized to 0. - A
while
loop is started, which continues as long assteps
is less thanheight
. - Inside the loop:
steps
is incremented bytime_step
.steps
is decremented bytime_step // 3
(integer division).time_step
is incremented by 1.
- After the loop ends, the values of
time_step
andsteps
are printed using theprint()
function with the format string"{}, {}"
.
- The variable
- The function
elephant()
is called with different arguments:elephant(0)
:- The loop is not executed since
steps
(0) is not less thanheight
(0). - The values of
time_step
(1) andsteps
(0) are printed.
- The loop is not executed since
elephant(5)
:- The loop iterates until
steps
becomes greater than or equal toheight
(5). - In each iteration:
steps
is incremented bytime_step
(1, 2, 3, 4).steps
is decremented bytime_step // 3
(0, 0, 1, 1).time_step
is incremented by 1.
- After the loop ends, the values of
time_step
(5) andsteps
(5) are printed.
- The loop iterates until
elephant(6)
:- The loop iterates until
steps
becomes greater than or equal toheight
(6). - The loop behaves similarly to the previous case, but since
height
is 6, the loop ends whensteps
becomes 6. - After the loop ends, the values of
time_step
(5) andsteps
(6) are printed.
- The loop iterates until
- The program ends.
Therefore, the output will be:
|
|
Code Output 3
Show the output of the following code. Make sure we can determine what is output and what is scratch work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
def remove_something(z): z.remove( z[z[0]] ) v = [ 1, 8, [12, 8], 'hello', 'car' ] x = 'salad' if len(v[2]) >= 2: if x > v[3]: print( 'One') if v[0] == 1: print('Three') else: print('Two') elif len(v) == 5: print('Six') else: v.append('five') print('Ten') remove_something(v) print(v[1]) print(v[2]) v.append(x) print(len(v))
Answer of This Question
Output:
|
|
Explanation:
- The function
remove_something(z)
is defined, which removes the element at indexz[0]
from the listz
. - The list
v
is initialized with the values[1, 8, [12, 8], 'hello', 'car']
. - The variable
x
is assigned the string value'salad'
. - The
if
conditionlen(v[2]) >= 2
is evaluated:v[2]
is[12, 8]
, and its length is 2, so the condition is true.
- The
if
conditionx > v[3]
is evaluated:x
is'salad'
andv[3]
is'hello'
. Since'salad'
is lexicographically greater than'hello'
, the condition is false.
- The
elif
conditionlen(v) == 5
is evaluated:len(v)
is 5, so the condition is true.- The string
'Six'
is printed.
- The function
remove_something(v)
is called withv
as the argument:- Inside the function,
z[0]
is 1, soz[z[0]]
isz[1]
, which is 8. - The element 8 is removed from the list
v
.
- Inside the function,
v[1]
is printed, which is now[12, 8]
(since 8 was removed from the list).v[2]
is printed, which is now'hello'
(since the element at index 1 was removed).- The string
x
('salad'
) is appended to the listv
. len(v)
is printed, which is now 5 (since one element was removed and one element was added).- The program ends.
Therefore, the output will be:
|
|
Print Grid
You are given a list of lists represented as an NxN grid in which each list corresponds to one row of the grid. For example, a 4x4 grid is given by:
1
[[1,2,3,4],[4,3,2,1],[2,1,4,2],[2,1,4,5]]
Write a piece of code to print the grid in the following format with a vertical and horizontal line right in the middle:
1 2 3 4 5
1 2 | 3 4 4 3 | 2 1 ----|---- 2 1 | 4 2 2 1 | 4 5
Answer of This Question
Here’s the Python code to print the grid in the desired format:
|
|
Explanation:
-
The function
print_grid
takes a list of listsgrid
as input, representing the NxN grid. -
We calculate the length of the grid
n
and the middle indexmid
by dividingn
by 2 using integer division (//
). -
We start a loop that iterates over each row of the grid using the index
i
. -
For each row, we retrieve the current row
row
from the grid usinggrid[i]
. -
We start another loop that iterates over each element of the current row using the index
j
. -
Inside the inner loop, we check if the current column index
j
is equal to the middle indexmid
. If it is, we print a vertical bar (|
) followed by a space. -
We print the current element
row[j]
followed by a space. -
After printing all the elements of the current row, we move to the next line using
print()
. -
After printing each row, we check if the current row index
i
is equal tomid - 1
. If it is, we print a horizontal line (-
) of lengthn * 2 + 1
(the number of elements in each row multiplied by 2 plus 1 for the vertical bar). -
Finally, we provide an example usage of the
print_grid
function by creating a 4x4 grid and calling the function with the grid as an argument.
The output will be:
|
|
This code prints the grid in the desired format, with a vertical bar (|
) in the middle of each row and a horizontal line (-
) in the middle of the grid.
Sum and Count Numbers
Write a piece of code that repeatedly asks the user for numbers using input until the user enters ‘stop’. Then, the program reports the sum of the values entered by the user and the total number of values strictly greater than zero. You can assume that the user enters a valid number until she enters stop.
An example run of this code is given below.
1 2 3 4 5 6 7
Enter a value ==> 1.2 Enter a value ==> 0 Enter a value ==> 2 Enter a value ==> -1 Enter a value ==> stop Sum: 2.2 Values > 0: 2
Answer of This Question
Here’s the Python code that repeatedly asks the user for numbers until ‘stop’ is entered, and then reports the sum of the values and the count of values strictly greater than zero:
|
|
Explanation:
-
The function
sum_and_count_numbers
is defined to perform the desired task. -
We initialize two variables:
total_sum
to keep track of the sum of all the numbers entered by the user, andcount_positive
to count the number of values strictly greater than zero. -
We start an infinite loop using
while True
to repeatedly ask the user for input. -
Inside the loop, we prompt the user to enter a value using
input()
and store it in theuser_input
variable. -
We check if the
user_input
is equal to ‘stop’. If it is, we break out of the loop using thebreak
statement, indicating that the user wants to stop entering values. -
If the
user_input
is not ‘stop’, we attempt to convert it to a float usingfloat()
and store it in thenumber
variable. We use atry-except
block to handle any potentialValueError
that may occur if the user enters an invalid input. -
If the conversion to float is successful, we add the
number
to thetotal_sum
using the+=
operator. -
We then check if the
number
is strictly greater than zero using the conditionnumber > 0
. If it is, we increment thecount_positive
variable by 1. -
If a
ValueError
occurs during the conversion to float, we catch the exception and print an error message to inform the user to enter a valid number. -
After the loop ends (when the user enters ‘stop’), we print the
total_sum
andcount_positive
values usingprint()
. -
Finally, we provide an example usage of the
sum_and_count_numbers
function by calling it.
The code will repeatedly prompt the user to enter values until ‘stop’ is entered. It will calculate the sum of all the entered values and count the number of values strictly greater than zero. The output will be similar to the example run provided in the question.
Remove Value from List
Write a function
remove_val(l,val)
that removes all copies ofval
from listl
.Suppose you are given a variable
x
containing numbers as shown below:
1
x = [1, 4, 2, 1, 2, 4, 4, 2, 5, 5, 2]
Then, your function should work as follows:
1 2 3
>>> remove_val(x,4) >>> x [1, 2, 1, 2, 2, 5, 5, 2]
Note: if your function returns a new list with this content instead of modifying it as given, you will lose points. Also, be careful with this one. The code:
(a)
1 2 3 4
def remove_val(l,val): for item in l: if item == val: l.remove(val)
and
(b)
1 2 3 4
def remove_val(l,val): for index in range(len(l)): if l[index] == val: l.pop(index)
will not work. Can you explain why? Try writing (a) using a while loop and see if that makes it clearer. For (b) try running it in the debugger.
Answer of This Question
Here’s the correct implementation of the remove_val
function that removes all occurrences of val
from the list l
:
|
|
Explanation:
- The function
remove_val
takes two parameters:l
(the list) andval
(the value to be removed). - We use a
while
loop to repeatedly check ifval
is present in the listl
using thein
operator. - If
val
is found in the list, we remove it using thelist.remove()
method. - The loop continues until all occurrences of
val
are removed from the list.
Now, let’s discuss why the two given implementations (a) and (b) do not work correctly:
(a) Using a for
loop:
|
|
Explanation:
- The problem with this implementation is that it modifies the list while iterating over it using a
for
loop. - When an element is removed from the list, the indices of the subsequent elements shift, causing the loop to skip some elements.
- As a result, not all occurrences of
val
are removed from the list.
(b) Using range()
and pop()
:
|
|
Explanation:
- This implementation also suffers from the same issue as (a).
- When an element is removed using
pop()
, the indices of the subsequent elements shift. - However, the loop continues to the next index, potentially skipping elements that match
val
. - Consequently, not all occurrences of
val
are removed from the list.
To understand the issue more clearly, you can run the code in a debugger and step through it to see how the indices change after each removal.
The correct approach is to use a while
loop as shown in the first implementation. It repeatedly checks for the presence of val
in the list and removes it until all occurrences are eliminated.
Example usage:
|
|
The function modifies the original list x
by removing all occurrences of the value 4
.
Compare Athlete Scores
Suppose you are given the scores of two athletes in various competitions, provided as two separate lists. Assume there are unknown number of competitions numbered 1,2,3, etc. and the length of the two lists is the same.
1 2
a1 = [11,8,11,9] a2 = [11,9,8,12]
For example according this to list, both athletes got a score of 11 in competition 1. Print the index of all the competitions in which
a2
did better. For example, for the above lists, we would print:
1
a2 is better in 2 4
If there is no value in which
a2
is better, then you should print:
1
a2 is never better
Answer of This Question
Here’s a Python script that compares the scores of two athletes in various competitions and prints the index of the competitions in which a2
did better:
|
|
Explanation:
-
The function
compare_scores
takes two listsa1
anda2
as parameters, representing the scores of two athletes in various competitions. -
We initialize an empty list called
better_indices
to store the indices of the competitions in whicha2
did better. -
We start a loop that iterates over the indices of the scores using
range(len(a1))
. Since both lists are assumed to have the same length, we can use the length of either list. -
Inside the loop, we compare the scores of
a2
anda1
at each index using the conditiona2[i] > a1[i]
. Ifa2
has a higher score at the current index, we append the index plus 1 to thebetter_indices
list. We add 1 to the index because the competitions are numbered starting from 1. -
After the loop ends, we check if the
better_indices
list is not empty using anif
statement. -
If
better_indices
is not empty, it meansa2
did better in at least one competition. We print “a2 is better in” followed by the indices of the competitions wherea2
did better. We use thejoin()
method to concatenate the indices into a string, separated by spaces. Themap(str, better_indices)
is used to convert the indices to strings before joining them. -
If
better_indices
is empty, it meansa2
did not do better in any competition. In this case, we print “a2 is never better”. -
Finally, we provide an example usage of the
compare_scores
function by calling it with the given listsa1
anda2
.
The output for the example lists will be:
|
|
This indicates that a2
did better in competitions 2 and 4.
If a2
never did better in any competition, the output will be:
|
|
This script compares the scores of two athletes and prints the indices of the competitions in which a2
did better, or “a2 is never better” if a2
did not do better in any competition.
List Slicing Output
What is the output from the following code:
1 2 3 4 5 6 7 8 9
>>> L1 = ['cat', 'dog', 'hawk', 'tiger', 'parrot'] >>> print(L1[1:-1]) >>> print(L1[1:-2]) >>> print(L1[1:-4]) >>> print(L1[1:0]) >>> print(L1[1:10]) >>> print(L1[::-1]) >>> print(L1[1:4:2]) >>> print(L1[::-2])
Answer of This Question
Here’s the output from the given code:
|
|
Explanation:
-
print(L1[1:-1])
:- This slices the list
L1
from index 1 (inclusive) to the second-to-last index (exclusive). - The output is
['dog', 'hawk', 'tiger']
.
- This slices the list
-
print(L1[1:-2])
:- This slices the list
L1
from index 1 (inclusive) to the third-to-last index (exclusive). - The output is
['dog', 'hawk']
.
- This slices the list
-
print(L1[1:-4])
:- This slices the list
L1
from index 1 (inclusive) to the fifth-to-last index (exclusive). - Since there are only 5 elements in the list, this results in an empty slice.
- The output is
[]
.
- This slices the list
-
print(L1[1:0])
:- This slices the list
L1
from index 1 (inclusive) to index 0 (exclusive). - Since the ending index is less than the starting index, this results in an empty slice.
- The output is
[]
.
- This slices the list
-
print(L1[1:10])
:- This slices the list
L1
from index 1 (inclusive) to index 10 (exclusive). - Since the list has only 5 elements, the ending index goes beyond the list’s length, but it doesn’t cause an error. It simply includes all elements from index 1 to the end of the list.
- The output is
['dog', 'hawk', 'tiger', 'parrot']
.
- This slices the list
-
print(L1[::-1])
:- This slices the list
L1
with a step of -1, which reverses the list. - The output is
['parrot', 'tiger', 'hawk', 'dog', 'cat']
.
- This slices the list
-
print(L1[1:4:2])
:- This slices the list
L1
from index 1 (inclusive) to index 4 (exclusive) with a step of 2. - It includes every second element within the specified range.
- The output is
['dog', 'tiger']
.
- This slices the list
-
print(L1[::-2])
:- This slices the list
L1
with a step of -2, which reverses the list and includes every second element. - The output is
['parrot', 'hawk', 'cat']
.
- This slices the list
These examples demonstrate different ways of slicing a list in Python using start index, end index, and step size.
Code Output 4
What is the output of the following programs:
Part a
1 2 3 4 5 6 7 8 9 10 11 12
a = 25 b = 11 while True: print(a, b) if a <= 0 or b <= 0: break if a > b: a = a - b else: b = b - a b -= 1 a += 1
Part b
1 2 3 4 5
mylist = [10, -5, 4, 8, 1000, -1, -120, 18, 5.2] for item in mylist: if item < 0: continue print(item)
Part c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
def spam(l,s): m = len(s)//2 s1 = s[:m] s2 = s[m:] if l.count(s1) == 0: l.append(s1) if l.count(s2) == 0: l.append(s2) l = ['ab','cd','de','fg'] s1 = 'abcde' s2 = 'fghi' spam(l,s1) print(s1) l = spam(l,s2) print(s2) print(l)
Answer of This Question
Here’s the output of each program:
Part a
|
|
Explanation:
- The program starts with
a = 25
andb = 11
. - It enters an infinite loop and prints the values of
a
andb
in each iteration. - Inside the loop, it checks if either
a
orb
becomes less than or equal to 0. If so, it breaks out of the loop. - If
a
is greater thanb
, it subtractsb
froma
. Otherwise, it subtractsa
fromb
. - After the subtraction, it decrements
b
by 1 and incrementsa
by 1. - The loop continues until the break condition is met, and the program terminates.
Part b
|
|
Explanation:
- The program iterates over the elements in
mylist
. - For each element, it checks if the element is less than 0 using the condition
if item < 0
. - If the element is less than 0, it skips that element using the
continue
statement and moves to the next iteration. - If the element is greater than or equal to 0, it prints the element.
- The program continues until all elements in
mylist
have been processed.
Part c
|
|
Explanation:
- The program defines a function
spam
that takes a listl
and a strings
as parameters. - Inside the function, it calculates the middle index
m
of the strings
using integer division. - It splits the string
s
into two halves:s1
(from the start to the middle index) ands2
(from the middle index to the end). - It checks if
s1
is not present in the listl
usingl.count(s1) == 0
. If so, it appendss1
to the listl
. - Similarly, it checks if
s2
is not present in the listl
usingl.count(s2) == 0
. If so, it appendss2
to the listl
. - The program initializes a list
l
with['ab', 'cd', 'de', 'fg']
and two stringss1
ands2
. - It calls the
spam
function withl
ands1
as arguments. - It prints the value of
s1
, which remains unchanged. - It calls the
spam
function again withl
ands2
as arguments, but the return value is not assigned to any variable. - It prints the value of
s2
, which remains unchanged. - Finally, it prints the updated list
l
, which includes the original elements and the split halves ofs1
ands2
that were not already present in the list.
These programs demonstrate different concepts such as loops, conditionals, list manipulation, and function calls in Python.
More “What Is the Output?” Questions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
print(4**3) print(2**2**3) ---------------- for i in range(2,10,2): print(i) ---------------- j=2 while(j<10): print(j) j=j+2 L=[1,2,3,(7,8,'truck')] L.insert(-1,L.pop()) print(L) ---------------- pokeballs = ["net", "ultra", "dusk", "great", "great", "great"] while(True and pokeballs.pop() == "great"): print(pokeballs) print(pokeballs[-1] == "great") ---------------- list1 = [6,8,10] list2 = [[3,5,7], list1, list(list1)] list1.append(list2[0].pop()) print(list2) ---------------- j=11 while(True): print('-',end='') i=0 if i >= 5: break elif j <= 4: break j = j - 1 if j%2 == 1: continue print('*',end='') i = i + 2 ---------------- a = "and".join(list("1234")) b = a.split('and') c = b b.append('5') c.append('6') print(a) print(b) print(c) c = b[:] b.append('7') c.append('8') print(b) print(c) ---------------- lst = ['dog', 'cat', 'chat'] print('dog' in lst and 'hat' in lst[2]) ---------------- print(not True or True and False == False) ---------------- symbols = ['5', 'p', 'P', '100', '!', 'pika', 'Pika', 'pIka', '44'] print(sorted(symbols)) print(symbols[::].sort()) print(symbols) print(symbols.sort()) print(symbols) print(symbols[::-1]) ---------------- def someFunc(myList, myTuple): myTuple = (4,3,2,1) for pikachu in myList: myList[pikachu-1] = str(pikachu) + "pika" return True aList = [1, 2, 3, 4] aTuple = (1, 2, 3, 4) if someFunc(aList, aTuple): print(aTuple) print(aList) ---------------- waterTypes = ["Oshawott", "Froakie", "Squirtle", "Kyogre"] print(waterTypes[0:3:2]) print(waterTypes[1::2]) print(waterTypes[-1:0:-2]) print(waterTypes[-2::-2]) wT2 = waterTypes[0:4:1].append("Magikarp") print(wT2) wT2 = waterTypes[0:4:1] print(wT2) print(wT2[:1] + wT2[-3:3] + wT2[-2:-3] + wT2[3:] + ["Magikarp"])
Answer of This Question
Here’s the output for each code snippet:
|
|
Explanation for each code snippet:
-
4**3
evaluates to 64, and2**2**3
evaluates to 256 due to the right-to-left associativity of the exponentiation operator (**
). -
The
for
loop prints the even numbers from 2 to 8 (inclusive) with a step of 2. -
The
while
loop prints the even numbers from 2 to 8 (inclusive) with a step of 2. -
The last element of the list
L
is popped usingL.pop()
and inserted at the second-to-last position usingL.insert(-1, ...)
. The resulting list is printed. -
The
while
loop iterates until the last element ofpokeballs
is not equal to “great”. In each iteration, it prints the current state ofpokeballs
and the result of the comparisonpokeballs[-1] == "great"
. -
The last element of
list2[0]
is popped and appended tolist1
. The resultinglist2
is printed. -
The
while
loop prints a pattern of dashes and asterisks based on the conditions and iterations. -
The string “1234” is split into a list, joined with “and”, split again, and the resulting list is modified by appending elements. The variables
a
,b
, andc
are printed at different stages. -
The expression
'dog' in lst and 'hat' in lst[2]
evaluates toTrue
because both conditions are true. -
The expression
not True or True and False == False
evaluates toTrue
due to the order of operations and the truthiness of the operands. -
The list
symbols
is sorted in ascending order usingsorted()
, and the result is printed. Thesort()
method is called onsymbols
and its slices, modifying the original list. The reversed list is printed using slicing with a step of -1. -
The function
someFunc
modifies the elements ofaList
by appending “pika” to each element. The tupleaTuple
remains unchanged. The modifiedaList
and the originalaTuple
are printed. -
Various slicing operations are performed on the
waterTypes
list, and the results are printed. Theappend()
method is called on a slice ofwaterTypes
, but the returned value isNone
. The last line concatenates slices ofwT2
and a new element “Magikarp” to create a new list.
Remove Elements from List 1
And a final, really hard one … Ask about it and we can go over why in review.
1 2 3 4 5 6 7 8
r = 10*[1] for i in range(len(r)): r.remove(1) print(r) L = 10*[1] for l in L: L.remove(l) print(L)
Answer of This Question
The code snippet you provided demonstrates two different ways of attempting to remove elements from a list, but both approaches have issues. Let’s analyze each case:
Case 1:
|
|
Explanation:
- The list
r
is initialized with 10 occurrences of the value1
. - The
for
loop iterates over the indices ofr
usingrange(len(r))
. - In each iteration, the first occurrence of
1
is removed fromr
usingr.remove(1)
. - However, as elements are removed from the list, the indices of the remaining elements shift.
- The loop continues to the next index, potentially skipping elements.
- As a result, only the first 5 occurrences of
1
are removed, and the final listr
contains[1, 1, 1, 1, 1]
.
Case 2:
|
|
Explanation:
- The list
L
is initialized with 10 occurrences of the value1
. - The
for
loop iterates over the elements ofL
directly. - In each iteration, the first occurrence of the current element
l
is removed fromL
usingL.remove(l)
. - However, modifying the list while iterating over it using a
for
loop leads to unexpected behavior. - As elements are removed, the indices of the subsequent elements shift, causing the loop to skip some elements.
- Consequently, only alternate occurrences of
1
are removed, resulting in the final listL
containing[1, 1, 1, 1, 1]
.
In both cases, the desired outcome of removing all occurrences of 1
from the list is not achieved.
To correctly remove all occurrences of an element from a list, you can use a while
loop as shown in the previous answer:
|
|
This approach repeatedly checks for the presence of val
in the list l
and removes it until all occurrences are eliminated.
Example usage:
|
|
In both cases, all occurrences of 1
are successfully removed from the lists r
and L
, resulting in empty lists.
It’s important to be cautious when modifying a list while iterating over it, as it can lead to unexpected behavior. Using a while
loop or creating a new list with the desired elements are safer approaches.
Remove Elements from List 2
Okay not really a “What’s the Output” but similar. See if you can explain this one:
1 2 3 4
r = 10*[1] for i in range(len(r)): r.remove(r[i]) print(r)
Answer of This Question
The code snippet you provided attempts to remove elements from the list r
using a for
loop and the remove()
method, but it leads to unexpected behavior. Let’s analyze it step by step:
|
|
Explanation:
- The list
r
is initialized with 10 occurrences of the value1
. - The
for
loop iterates over the indices ofr
usingrange(len(r))
. - In each iteration, the element at index
i
is removed fromr
usingr.remove(r[i])
. - However, as elements are removed from the list, the indices of the remaining elements shift.
- The loop continues to the next index, which now corresponds to a different element than originally intended.
Let’s trace the execution of the code:
- Initially,
r
is[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
. - In the first iteration (
i = 0
),r[0]
is1
, so1
is removed fromr
. After removal,r
becomes[1, 1, 1, 1, 1, 1, 1, 1, 1]
. - In the second iteration (
i = 1
),r[1]
is now the second1
in the updated list. It is removed, andr
becomes[1, 1, 1, 1, 1, 1, 1, 1]
. - In the third iteration (
i = 2
),r[2]
is now the third1
in the updated list. It is removed, andr
becomes[1, 1, 1, 1, 1, 1, 1]
. - The loop continues, removing every other element from the list.
After the loop finishes, the resulting list r
will be [1, 1, 1, 1, 1]
.
The issue with this code is that it modifies the list while iterating over it using indices. As elements are removed, the indices of the subsequent elements shift, causing the loop to skip some elements and leading to unexpected behavior.
To correctly remove all occurrences of an element from a list, you can use a while
loop as shown in the previous answers:
|
|
This approach repeatedly checks for the presence of val
in the list l
and removes it until all occurrences are eliminated.
Example usage:
|
|
In this case, all occurrences of 1
are successfully removed from the list r
, resulting in an empty list.
It’s important to be cautious when modifying a list while iterating over it, as it can lead to unexpected behavior. Using a while
loop or creating a new list with the desired elements are safer approaches.
Related Content
- CSCI 1100 - Homework 4 - Loops and Lists; Passwords and Quarantine
- CSCI 1100 - Homework 5 - Lists of Lists; Grids; Path Planning
- CSCI 1100 - Homework 3 - Loops, Tuples, Lists, and Ifs
- CSCI 1100 - Homework 2 - Strings and Functions
- CSCI 1100 - Homework 1 - Calculations and Strings