7.14. Exercises

  1. In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop tries to output these names in order.

    Of course, that’s not quite right because Ouack and Quack are misspelled. Can you fix it?

  1. Get the user to enter some text and print it out in reverse order.

  1. Write a program that uses a for loop to print
    One of the months of the year is January
    One of the months of the year is February
    One of the months of the year is March
    etc …
    Show Comments
  1. Assume you have a list of numbers 12, 10, 32, 3, 66, 17, 42, 99, 20

    1. Write a loop that prints each of the numbers on a new line.

    2. Write a loop that prints each number and its square on a new line.

  1. Write a program that asks the user for the number of sides, the length of the side, the color, and the fill color of a regular polygon. The program should draw the polygon and then fill it in.

  1. A drunk pirate makes a random turn and then takes 100 steps forward, makes another random turn, takes another 100 steps, turns another random amount, etc. A social science student records the angle of each turn before the next 100 steps are taken. Her experimental data is 160, -43, 270, -97, -43, 200, -940, 17, -86. (Positive angles are counter-clockwise.) Use a turtle to draw the path taken by our drunk friend. After the pirate is done walking, print the current heading. Assume that the turtle originally has a heading of 0 and accumulate the changes in heading to print out the final. Your solution should work for any sequence of experimental data.

    Show Comments
  1. Write a program that will go through a list of temperatures and print them out to the user.

  1. Write a program that will print out a greeting to each student in the list. This list should also keep track of how many students have been greeted and note that each time a new student has been greeted.

7.14.1. Contributed Exercises

Get the user to enter some text and print out True if it’s a palindrome, False otherwise. (Hint: reuse some of your code from the last question. The == operator compares two values to see if they are the same)
This code is supposed to multiply all the elements in the list ‘lst’. However, the code is wrong and doesn’t produce the right result. Fix all the errors to get the desired result. Your code HAS to produce a single output: 24.

Q-1: After completing the reading, what concepts are still unclear to you? If nothing is unclear, what did you find most interesting?

Write a for loop that prints the odd numbers from 1 to 101.

The \(L^{2}\text{-norm}\) is the most common method for calculating the norm or magnitude of a vector. For an \(N\text{-dimensional}\) vector, the \(L^{2}\text{-norm}\) is calculated as

\[\left|\vec{v}\right|=\sqrt{ \sum_{i=1}^N v_i^{2}}.\]

For example, the norm of the vector \(\vec{v}=\left(3,0,-4\right)\) is

\[\left|\vec{v}\right|=\sqrt{\left(3\right)^{2}+\left(0\right)^{2}+\left(-4\right)^{2}}=5.\]

Compute and print out the \(L^{2}\text{-norm}\) of the vectors defined below.

The wavelengths of the spectral lines from hydrogen are given by the Balmer series

\[\frac{1}{\lambda} = R_\text{H}\left(\frac{1}{2^2} - \frac{1}{n^2}\right)\quad n=3,4,5,\dots\]

where \(\lambda\) is the wavelength in m and \(R_\text{H}=1.0974\times10^7~\text{m$^{-1}$}\). Using a for-loop, compute the wavelengths of the first five spectral lines and store them in a list called wavelengths.

In the code below, a \(3\times3\) matrix has been define for you. Using loops, update this matrix by scalar multiplying by 5.7.

Hint: you will need two nested loops.

The average monthly rainfall in inches recorded at the Van Nuys Airport for 2018 is stored in the rainfall variable provided below. Using a loop, calculate and print out the

  1. total,

  2. mean, and

  3. standard deviation,

each on a separate line.

The standard deviation is given by

\[\sigma = \sqrt{\frac{1}{N-1}\sum_{i=1}^N (x_i - \bar{x})^2 },\]

where \(\bar{x}\) is the mean.

Do not use the sum() function. You should calculate all three values using two loops.

The average monthly rainfall in inches recorded at the Van Nuys Airport for 2018 is stored in the rainfall_in variable provided below. Using a loop, calculate and print out the

  1. total,

  2. mean, and

  3. standard deviation,

in centimeters, each on a separate line.

The standard deviation is given by

\[\sigma = \sqrt{\frac{1}{N-1}\sum_{i=1}^N (x_i - \bar{x})^2 },\]

where \(\bar{x}\) is the mean.

Do not use the sum() function.

In Robert McCloskey’s book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop tries to output these names in order.

Of course, that’s not quite right because Ouack and Quack are misspelled. Can you fix it?

Get the user to enter some text, save it to a variable called user_input, and print it out in reverse order.

Get the user to enter some text, save it to a variable called user_input, and print out True if it’s a palindrome, False otherwise. (Hint: reuse some of your code from the last question. The == operator compares two values to see if they are the same)

Assume you have a list of numbers 12, 10, 32, 3, 66, 17, 42, 99, 20

  1. Write a loop that prints each of the numbers on a new line.

  2. Write a loop that prints each number and its square on a new line.

This code is supposed to multiply all the elements in the list lst. However, the code is wrong and doesn’t produce the right result. Fix all the errors to get the desired result. Your code HAS to produce a single output: 24.

Compute and output

\[\sum_{i=0}^{100} i\]

Evaluate and output

\[f(x) = x^2\]

for

\[x=0,0.2, 0.4, 0.8\dots,1.6,1.8,2.0\]

In the code below, two \(3\times3\) matrices, mat1 and mat2, have been defined for you. Using a loops, multiply these together without changing either one and assign the result to a variable called mat3.

Hint: you will need three nested loops.

Hint: it is easier if you create mat3 first as a \(3\times3\) of all zeros.

The below lists contain information on groceries: the SKU code, product category, brand, product name, price, and unit size.

Your program should allow the select a report to display. The reports should display:

  1. The number of products from each brand.

  2. A listing of all products with their SKU code, product name, price, unit size, and per-unit cost.

  3. The average per-unit cost for each product category.

You can add additional features to the program if you like.

You may use features and modules not covered in class. If your code requires modules not supported by Runestone to run, please indicate that in a comment and list where you have successfully run your program.

Write a program that computes the sum of the squares of the items in the list numbers and prints the result. Choose your variable names appropriately. Make sure to write your code so that it works no matter how many items are in the list. Hint, the answer for the given list is 187 (because 4 + 9 + 25 + 49 + 100 = 187).

Write a program that iterates through each character of the string test_string and does the following. If the character is an "a", print You get an apple!; if instead the character is a "b", print You get a banana!; otherwise, print No fruit for you! Choose your variable name(s) appropriately. Just to be clear, your program should print as many lines as there are characters in test_string.

A 2-dimensional table of numbers (also called a matrix) can be realized in Python with a list of lists. In the code segment below, a table with 3 rows and 4 columns has been defined, with the assignment statement split over three lines for readability. Run the code to see what the table looks like when printed.

It’s a good idea not to hardcode the number of rows and columns. Don’t forget the table is a list of lists, so the number of rows is the length of the outer list, and the number of columns is the length of any one of the inner lists (so we might as well use the first one). Also, this time we use the accumulator pattern to sum up all of the numbers in the table. Check out the new code and run it.

Next let’s mutate the table! We’ll simply add 10 to each number in the table and then print the table (just using the list of lists format) to see the result. Check out the new code and run it.

Now it is your turn! Using nested for loops, multiply each number in the table by 5 (try not to copy and paste from previous code segments!). If you want to print the table, feel free, but that’s not required.

Q-1: If table = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], what is the value of table[0][0]?

Q-1: If table = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], what is the value of table[1][2]?

Q-1: If table = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], what is the value of table[2][3]?

We can print each number of the table on a separate line using nested for loops. The outer for loop iterator variable i indexes the 3 rows, and the inner for loop iterator variable j indexes the 4 columns. Run the code and study the output to make sure you see how the nested for loops work.

While i and j are standard iterator variables in this situation, row and col might be more descriptive. Also we can print the values of the table in a more readable format by using the named parameter end of the print() function to change what is printed at the end of the line, which by default is the newline character \n, to simply a space. We then need a print statement within only the outer for loop in order to get each row to be on a new line. Check out the new code and run it.

In this code segment, there are two tables, table1 and table2, each with 3 rows and 4 columns. Using nested for loops, create a new table called table3 (having 3 rows and 4 columns), so that each number in table3 is the sum of the corresponding numbers in table1 and table2. Hint: before the nested for loops, define table3 to be a table having all zeros, and then overwrite the zeros one by one in the innermost loop.

Write a program that will rotate an image by any arbitrary degree. Your code must create an output image that is large enough to contain all of the original image without cropping.

The provided calculate_rotation() function will determine the adjusted location of a pixel after it has been rotated. The function returns a tuple, where the first element is the rotated X coordinate and the second element is the rotated Y coordinate.

Consider the list given below. Write the program that uses a for loop will to print each item of the list on the separate line.

Now, write a program that will print the length for each string in the list below.

Write a program that will calculate the sum of all lengths of the strings below and store the sum in variable sum_of_lengths. Then find the average length of the strings and store it in average_length variable.

Write a program that will create a dictionary called my_dictionary out of the list of strings below where the keys are each word from the list, and the values are the counts of how many times each word occurs in the list. Your result should be the following dictionary:

“”:2

“hello”: 2

“goodbye”: 2

“I love Python”: 1

“wonderful”: 1

(You might get a different order of elements)

Ask the user for a integer i. Use a for loop to find i*i*i*i (aka \({i}^{4}\)) and save this to the variable g.

Output the sequence of numbers

\[0,0.2, 0.4, 0.6\dots,1.6,1.8,2.0\]

with one value on each line.

Write a program that uses the accumulator pattern (for loop) to sum all the number in the list below and assign the sum to a variable called my_sum. (Note: you have to use the for loop and accumulator pattern. No hard coding!)

Write a program that calculates the average word length of the words found in sentence. Store the average in a variable named average.

Design, implement, and fully test a Python3 function that converts a number to words (words_from_number(number: int)). It should expect to be passed a natural number (such as 12345) and return the corresponding words (i.e., “twelve thousand three hundred forty-five”). Since Python integers can grow arbitrarily large, your code should be flexible, handling at least 20 digits (realistically, it’s just as easy up to 30 digits). Spell everything correctly, and use correct punctuation (hyphens for forty-five and thirty-seven, no commas or plurals). You may only use built-in Python functions, not any modules or third-party libraries!

Compute and print the following using a for loop:

\[\sum_{i=50}^{100} i\]

If you are unable to see the above math equation, it should read “the sum of all numbers from 50 to 100 inclusive”

Given the list numList, write code that produces a list named squareList.

squareList should be a “parallel” list that contains the square of each corresponding number in numList.

Your code should work regardless of the values in numlist. Do not hard code this. Use a loop.

Consider the code given below. Make the red value in each pixel equal to 0. In other words, keep the green and blue the same, but change the red to 0.

Create the function filter_strings below to take a list of strings str_list and return a new list with all the strings from the passed list in the same order that have a length greater than 3. For example, filter_strings(["Run", "she", "said"]) should return ["said"] and filter_strings(["It", "was", "a", "dark", "night"]) should return ["dark", "night"]. There are three extra code blocks that are not needed in a correct solution.

Once you have completed the coding problem above, construct your solution explanation video and submit it (the video) in response to the HW05 assignment on the course Canvas page. (See Canvas for more details.)

Predict what will be printed by this code BEFORE you run it.

Be ready to explain the results.

Once you have completed the coding problem above, construct your solution explanation video and submit it (the video) in response to the HW06 assignment on the course Canvas page. (See Canvas for more details.)

Predict what will be printed by this code BEFORE you run it.

Be ready to explain the results.

GameStop Stock!

gme_daily is a string with a list of daily closing prices of the GameStop stock separated by the , sign. Write code that uses the accumulation pattern to compute the average (sum divided by number of items) and assigns it to gme_daily_avg. Print a meaningful message to the user stating what has been computed.

To be eligible to earn full credit:

  1. Do not hard code your answer (i.e., your code should work even if the gme_daily list is modified.)

  2. Use meaningful identifiers for your variables.

  3. Include appropriate comments in your code describing what blocks of your code are doing.

This code is supposed to produce an acronym which is a concatenation of the first letter of each word (capitalized) in lst. However, the code is wrong and doesn’t produce the right result. Fix all the errors to get the desired result (without hardcoding). Your code HAS to produce a single output, MAPS, which is stored in the variable acronym.

Write a program by completing the following:

  1. Prompt the user to enter a color and store the user’s input in a variable named clr.

  2. Instantiate a turtle object, make it turtle-shaped, and make it the color provided by the user.

  3. Without leaving a mark, move the turtle to the very bottom center of the window and facing north.

  4. Generate a random integer between -10 and 10 (inclusive) and store it in a variable called angle. Make the turtle turn that angle (a positive value makes the turtle turn right/east, a negative value left/west) and walk forward (north’ish) a distance of 8, this time leaving a mark.

  5. Repeat Step 4 so that the turtle turns (randomly) and walks forward/north’ish a total of 50 times.

  6. Compute the average of the angles turned by the turtle and print the result in a nice message.

Extra Credit:

Modify the program so that the user provides a list of colors separated by commas. Make the turtle change colors each time it moves forward so that it cycles through the colors provided by the user. For example, if the user enters red, blue, green then the turtle should change from red to blue, to green, to red, to blue, to green, etc.

Once you have completed the coding problem above, construct your solution explanation video and submit it (the video) in response to the HW09 assignment on the course Canvas page. (See Canvas for more details.)

Write a for loop that prints the odd numbers from 1 to 101, with one value on each line.

One of the easiest methods for numerically integrating functions is the trapezoidal method. To compute the integral, we evaluate the function at regular intervals, \(\Delta x\), starting from the lower bound and concluding with the upper bound and combining the result as

\[\int_a^b f(x) \approx \Delta x \left( \frac{f(a) + f(b)}{2} + \sum_{k=1}^{N-1} f(x_k)\right)\]

When computing integrals like this, it is best to determine \(\Delta x\) from the number of evaluation point rather than the other way around. I.e., if you wish to evaluate the integral from a to b using N=10, then

N = 10
dx = (b-a)/(N-1)

This prevents problems with round-off error when your interval is not precisely divisible by your \(\Delta x\).

Use the trapezoidal method to evaluate the integral

\[\int_0^2 x^2\, dx\]

with N=11 and print the result.

Once you have completed the coding problem above, construct your solution explanation video and submit it (the video) in response to the HW10 assignment on the course Canvas page. (See Canvas for more details.)

The code below is supposed to multiply all the elements in the list lst. However, the code is wrong and doesn’t produce the correct result. (Click the “Show Code” button if you do not see the code window.)

Fix all the errors to get the desired result. Your code has to produce a single output: 24. This question is worth 2 points.

The code below is supposed to multiply all the elements in the list lst. However, the code is wrong and doesn’t produce the correct result. (Click the “Show Code” button if you do not see the code window.)

Fix all the errors to get the desired result. Your code has to produce a single output: 24. This question is worth 2 points.

Once you have completed the coding problem above, construct your solution explanation video and submit it (the video) in response to the HW12 assignment on the course Canvas page. (See Canvas for more details.)

Remember: the activity above is from our Graphing Kiva Data with Altair project in the Runestone textbook. You’ll recall that the “simple” graph you think will be correct is not. Be certain to analyze your graph to ensure that it is actually summarizing the correct information.

You have attempted of activities on this page