6.10. Exercises

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’)!

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
  • 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.

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!

Using indexing multiple the 6th number (5) in the list by the 10th number(7) in the list save this value to k. Then use indexing to determine the location of the 8 in the list, save this as j. Do not hardcode!

Create a list of tuples called TOTALS, where each tuple is like this: (country, total_loan_amount,total_time_to_rise,total_num_lenders).

Q-1: Why cannot I do this?:

record = ('Ema', 'Stone', 'LA LA Land')

record[0] = 'Emma'

    Q-1: What is printed by the following statements?

    alist = [3, 67, "cat", [56, 57, "dog"], [ ], 3.14, False]
    print(alist[2:4])
    
  • [ [ ], 3.14, False]
  • No, this slice starts at index 4 and goes up to and including the last item.
  • ["cat", [56, 57, "dog"]]
  • Yes, "cat is at index 2 and [56, 57, "dog"] is what you get when index 4 is exclusive.
  • [ [56, 57, "dog"], [ ], 3.14, False]
  • Index values start at 0.

Write a Python program that

  1. prompts the user to enter a string, then

  2. prompts for an integer, representing how many random characters to print from that string.

The program should then use a loop to print that many random characters from the string, one per line.

Hint: use random.randrange within the loop, to generate a valid position in the string, then print the character at that position. Remember that len(myStr) will return the number of characters in myStr. Also remember that the positions or indexes in a string are numbered from right to left beginning with 0.

Example: The user enters My dog has fleas as their string, and 3 when prompted for the number of characters to print. A sample run of that scenario is shown below, presuming the random positions your code generated were 3, 15, and 0.:

Enter a string: My dog has fleas
How many random characters?  3

d
s
M

Write a Python program that prompts the user to enter a sentence. The program should then print out the number of times each lowercase vowel (i.e. a, e, i, o, and u), appears in that sentence.

I have provided the code to generate the output, so insert the required code above that. Do not include any additional print statements in your program.

You have attempted of activities on this page