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.temperatures = [-3, 78, 95, 28, 56, 42, 56, 81, -10, -]
    ---
    for temp in temperatures:
    ---
        print("The weather outside is: " + str(temp))
            
  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.students = ["Jay", "Stacy", "Iman", "Trisha", "Ahmed", "Daniel", "Shadae", "Tosin", "Charlotte"]
    ---
    num_students = 0
    ---
    for student in students:
    ---
        print("Welcome to class, " + student)
    ---
        num_students += 1
        print(str(num_students) + "student(s) have entered the classroom")
            

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: Construct a block of code that correctly implements the accumulator pattern.x = 0
======
for i in range(10)
   x = x + 1
        

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.

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

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\]

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.

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.

You have attempted of activities on this page
Next Section - 7.15. Chapter Assessment