6.10. Exercises

  1.         : Write a program that will print out the length of each item in the list as well as the first and last characters of the item.weather = ["sunny", "cloudy", "partially sunny",
               "rainy", "storming", "windy", "foggy",
               "snowy", "hailing"]
    ---
    for condition in weather:
    ---
        print("The word is", len(condition), "characters")
    ---
        first_char = condition[0]
        last_char = condition[-1]
    ---
        print("The first character is: " + first_char)
        print("The last character is: " + last_char)
            
  2.         : Write code to determine how many t's are in the following sentences.phrases = ["My, what a lovely day today is!",
    "Have you mastered cooking yet? A tasty treat could be in your future.",
    "Have you ever seen the leaves change color?"]
    ---
    for sentence in phrases:
    ---
        print(sentence.count("t"))
            

6.10.1. Contributed Exercises

Consider the list below in the activecode. Write the expressions doing the following:

  1. Print letter ‘C’ from this list
  2. Print letters ‘C’, ‘D’, ‘E’
  3. Print the length of this list
  4. Print the first element of this list
  5. Print the last element of this list
  6. Create a variable called grade and assign the third element (‘C’) from list letters list to it (print variable grade to make sure you did the right indexing)

Warning: for all printouts use indexing and the name of the list (letters). You cannot do print(‘C’)!

Q-1: Why cannot I do this? record = ('Ema', 'Stone', 'LA LA Land') record[0] = 'Emma'

Assign the value of the last chacter of ‘lst’ to the variable ‘output’. Do this so that the length of ‘lst’ doesn’t matter.
    Q-1: Assume that variable a is initialized to 3 with this line of code: a = 3. Match each piece of code on the left, to the right final value of 'a' on the right if you execute each of the expressions on the left independently.
  • a *= 2
  • 6
  • a = square(a)
  • 9
  • b = square(a)
  • 3
    Q-1: Assume that variable a is initialized to 3 with this line of code: a = 3. Match each piece of code on the left, to the right final value of a on the right if you execute each of the expressions on the left independently.
  • a = a + 1
  • 4
  • a = a
  • 3
  • a -= 2
  • 1
  • b = a + 1
  • 3
  • a = square(a)
  • 9
  • b = square(a)
  • 3
    Q-1: Assume that variable a is initialized to 3 with this line of code: a = 3. Match each piece of code on the left, to the right final value of 'a' on the right if you execute each of the expressions on the left independently.
  • a = a + 1
  • 4
  • b = a + 1
  • 3
  • a -= 2
  • 1
  • a = len("Hey there!")
  • 10
  • a = square(a) - 1
  • 8
Write code that combines the following variables so that the sentence “Now I know how to concatenate strings in Python!” is assigned to the variable ‘progress’. Do not edit the values assigned to by, m1, m2, m3 and m4.
Given the list in activecode below write the code to do the following:
  1. print 5th element from the list (‘?’) using list indexing
  2. using list indexing, take elements from the list ls to create a new variable called message containing “who run the world? girls”
  3. Capitalize the first word of the message variable so that it prints “Who run the world? girls”
Given the list in activecode below use list indexing to print the type of the 4th element (‘lights’) and 7th element (‘1’) of ls1. Did you get what you expected? Did you expect ‘1’ to be an integer? Now do the same for ls2. You notice that now you get a different result. Compare and analyse why.
Create a list containing any 6 shopping items of your choice. Use join to combine them in a single string separated with word ‘then’. Make sure that there is a space between the joined groceries like in: ‘eggs then milk then cocoa’
Create a string representing a quote from the first black woman in space Mae Jemison. She said: “We look at science as something very elite, which only a few people can learn. That’s just not true. You just have to start early and give kids a foundation. Kids live up, or down, to expectations.” Now use the split function to split this quote into four pieces based on the occurrence of the period punctuation.
Let us create a simple funny nickname generator. We will refine it in the future when we learn more tools. To do that, randomly generate the first name from the adjectives list, and the last name from the noun list given below in the code. Before you inform the user of the generated nickname, make sure you capitalize both the first and the last name (use the appropriate function, do not hard code!). The user should see something like this: Your nickname is: Squishy Panda. Make sure you use indexing and the random number generator. Every time you run your finalized code, something else should be printed, without you changing anything in your code! Do not hard code! You cannot write: print(‘Your nickname is’, ‘Squishy’, ‘Panda’)

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

Assign the value of the last character of ‘lst’ to the variable ‘output’. Do this so that the length of ‘lst’ doesn’t matter.

Write code that combines the following variables so that the sentence “Now I know how to concatenate strings in Python!” is assigned to the variable ‘progress’. Do not edit the values assigned to by, m1, m2, m3 and m4.

Given the list in activecode below write the code to do the following:

  1. print 5th element from the list (‘?’) using list indexing,

  2. using list indexing, take elements from the list ls to create a new variable called message containing “who run the world? girls”, and

  3. Capitalize the first word of the message variable so that it prints “Who run the world? girls”.

Given the list in activecode below use list indexing to print the type of the 4th element (‘lights’) and 7th element (‘1’) of ls1. Use one print statement for each element. Did you get what you expected? Did you expect ‘1’ to be an integer? Now do the same for ls2. You notice that now you get a different result. Compare and analyze why.

Create a string representing a quote from the first black woman in space Mae Jemison. She said: “We look at science as something very elite, which only a few people can learn. That’s just not true. You just have to start early and give kids a foundation. Kids live up, or down, to expectations.” Now use the split function to split this quote into four pieces based on the occurrence of the period punctuation and print each piece in order and one at a time.

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}$}\). Compute the wavelengths of the first five spectral lines and store them in a list called wavelengths.

We can represent a matrix in Python as a list of list s. We do this by creating a list in which each element is another list that contains row values. For example, the matrix

\[\begin{split}\mathbf{A}=\left[\begin{matrix}1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{matrix}\right]\end{split}\]

can be represented in Python as

a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]

Because Python will automatically continue lines with an ones parenthesis or bracket, we can also write it as

a = [ [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9] ]

We can then access element in row and column format. For example,

print(a[1][2])

writes out:

6

We can change values using the same approach. For example,

a[1][2] = 15
print(a)

writes out:

[[1, 2, 3], [4, 5, 15], [7, 8, 9]]

In the code below, define the matrix

\[\begin{split}\mathbf{A}=\left[\begin{matrix}17 & 18 & 19 & 20\\ 7 & 8 & 9 & 10\\ 1.7\times10^{-5} & 3.1 & 4 & 2\\ -7 & -8 & -9 & -7 \end{matrix}\right]\end{split}\]

and assign it to a variable called mat.

Another way to create a matrix is by combining several already define lists using the append() function. For example, the matrix

\[\begin{split}\mathbf{A}=\left[\begin{matrix}1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{matrix}\right]\end{split}\]

can be created from predefined rows as

a = []
row1 = [1, 2, 3]
row2 = [4, 5, 6]
row3 = [7, 8, 9]

a.append(row1)
a.append(row2)
a.append(row3)

In the code below, define the matrix

\[\begin{split}\mathbf{A}=\left[\begin{matrix}17 & 18 & 19 & 20\\ 7 & 8 & 9 & 10\\ 1.7\times10^{-5} & 3.1 & 4 & 2\\ -7 & -8 & -9 & -7 \end{matrix}\right]\end{split}\]

from the rows are already defined for you and assign it to a variable called mat.

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

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

Consider the list below in the activecode. Write the expressions to do the following:

  1. print letter ‘C’ from this list,

  2. print letters ‘C’, ‘D’, ‘E’ as a list,

  3. print the length of this list,

  4. print the first element of this list,

  5. print the last element of this list, and

  6. create a variable called grade and assign the third element (‘C’) from list letters list to it (print variable grade to make sure you did the right indexing).

Warning: for all printouts use indexing and the name of the list (letters). You cannot do print(‘C’)!

We want to use the slicing operator to create a list named recent_presidents containing the presidents elected starting with the 32nd president, Franklin D. Roosevelt.

We want to concatenate the elements of parts into a new variable named wv. Include spaces between each part.

The cross product of two 3-vectors, \(\vec{a}=(a_1, a_2, a_3)\) and \(\vec{b}=(b_1, b_2, b_3)\), is calculated as

\[\vec{a}\times\vec{b} = (a_2b_3 - a_3b_2, a_3b_1 - a_1b_3, a_1b_2 -a_2b_1).\]

For example, the norm of the vector \(\vec{a}=\left(3,0,-4\right)\) and \(\vec{b}=\left(1,2,3\right)\) is

\[\vec{a}\times\vec{b} = (8, -13, 6).\]

Ask the user for six values and store them as list s with type float and variable names vec_a and vec_b. Then print out \(\vec{a}\times\vec{b}\) as a list.

Create a list called shopping_list containing any 6 shopping items of your choice. Use join to combine them in a single string separated with word ‘then’ and print it to screen. Do not modify shopping_list. Make sure that there is a space between the joined groceries like in: ‘eggs then milk then cocoa’

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

\[\left|\vec{v}\right|=\sqrt{v_1^{2} + v_2^{2} + v_3^{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.\]

Ask the user for three values and store them as a list with type float with variable name vec. Then print out the \(L^2\text{-norm}\).

We want to see how many times Grover Cleveland was president. Store the result in a variable named grover_count.

Create a copy of the temps list such that it has all the temperature values in temps, but reduced by 10. The copy is called lower_temps and starts as an empty list. Use a for loop to iterate through the temps list and keep building lower_temps list.

Q-1: Compare lists and strings

Name and explain one thing they have in common

Q-1: Contrast lists and strings

Name and explain one thing that sets them apart.

The variable word references the string ‘winter’. Use for loops to create new strings with various text effects as follows.

  1. Variable long_word becomes ‘wwwiiinnnttteeerrr’

  2. Variable crossed_word becomes ‘XwXiXnXtXeXr’

Consider the list below in the activecode. Write the expressions to do the following:

  1. print letter ‘C’ from this list,

  2. print letters ‘C’, ‘D’, ‘E’ as a list,

  3. print the length of this list,

  4. print the first element of this list,

  5. print the last element of this list, and

  6. create a variable called grade and assign the third element (‘C’) from list letters list to it (print variable grade to make sure you did the right indexing).

Warning: for all printouts use indexing and the name of the list (letters). You cannot do print(‘C’)!

Replace each number in the list numbers with its square root. Your solution should work for any number of elements in the list.

Hint: use range() and len().

Use indexing to determine the first location of 5 in the list and save this as i. Determine the number of times 5` is present and save this as c. No for loop is needed. Don’t hardcode the answers I’m going to run it for a different L.

Use indexing to print the 6th through 9th values in the supplied list (there should be 4 total, traditional counting). Save the result to variable i. Don’t hardcode the result…I’m going to change L for my run!

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