Text
stringlengths
1
9.41k
Here is an example: L = [[1,2,3], [4,5,6], [7,8,9]] **Indexing** We use two indices to access individual items.
To get the entry in row r, column c, use the following: L[r][c] **Printing a two-dimensional list** To print a two-dimensional list, you can use nested for loops. The following example prints a 10 5 list: _×_ **for r in range(10):** **for c in range(5):** **print(L[r][c], end=" ")** **print()** Another option...
This function is used to “pretty-print” its argument.
Here is an example to print a list L: **from pprint import pprint** pprint(L) The pprint function can be used to nicely print ordinary lists and other objects in Python. **Working with two-dimensional lists** Nested for loops, like the ones used in printing a twodimensional list, can also be used to process the item...
Here is an example that counts how many entries in a 10 5 list are even. _×_ ----- _8.6.
TWO-DIMENSIONAL LISTS_ 71 count = 0 **for r in range(10):** **for c in range(5):** **if L[r][c]%2==0:** count = count + 1 This can also be done with a list comprehension: count = sum([1 for r in range(10) for c in range(5) if L[r][c]%2==0]) **Creating large two-dimensional lists** To create a larger list, you ...
Here we create a 5 5 5 list: _×_ _×_ L = [[[0]*5 for i in range(5)] for j in range(5)] It is a list whose items are lists of lists. The first entry in the list is L[0][0][0] ----- 72 _CHAPTER 8.
MORE WITH LISTS_ ###### 8.7 Exercises 1. Write a program that asks the user to enter some text and then counts how many articles are in the text. Articles are the words 'a', 'an', and 'the'. 2.
Write a program that allows the user to enter five numbers (read as strings). Create a string that consists of the user’s numbers separated by plus signs.
For instance, if the user enters 2, 5, 11, 33, and 55, then the string should be '2+5+11+33+55'. 3.
(a) Ask the user to enter a sentence and print out the third word of the sentence. (b) Ask the user to enter a sentence and print out every third word of the sentence. 4.
(a) Write a program that asks the user to enter a sentence and then randomly rearranges the words of the sentence.
Don’t worry about getting punctuation or capitalization correct. (b) Do the above problem, but now make sure that the sentence starts with a capital, that the original first word is not capitalized if it comes in the middle of the sentence, and that the period is in the right place. 5.
Write a simple quote-of-the-day program. The program should contain a list of quotes, and when the user runs the program, a randomly selected quote should be printed. 6.
Write a simple lottery drawing program. The lottery drawing should consist of six different numbers between 1 and 48. 7.
Write a program that estimates the average number of drawings it takes before the user’s numbers are picked in a lottery that consists of correctly picking six different numbers that are between 1 and 10.
To do this, run a loop 1000 times that randomly generates a set of user numbers and simulates drawings until the user’s numbers are drawn.
Find the average number of drawings needed over the 1000 times the loop runs. 8. Write a program that simulates drawing names out of a hat.
In this drawing, the number of hat entries each person gets may vary.
Allow the user to input a list of names and a list of how many entries each person has in the drawing, and print out who wins the drawing. 9.
Write a simple quiz game that has a list of ten questions and a list of answers to those questions. The game should give the player four randomly selected questions to answer.
It should ask the questions one-by-one, and tell the player whether they got the question right or wrong. At the end it should print out how many out of four they got right. 10.
Write a censoring program. Allow the user to enter some text and your program should print out the text with all the curse words starred out.
The number of stars should match the length of the curse word. For the purposes of this program, just use the“curse” words darn, dang, _freakin, heck, and shoot.
Sample output is below:_ Enter some text: Oh shoot, I thought I had the dang problem figured out. Darn it.
Oh well, it was a heck of a freakin try. Oh *****, I thought I had the **** problem figured out. **** [it. Oh well, it was a ]**** [of a ]****** [try.] ----- _8.7. EXERCISES_ 73 11.
Section 8.3 described how to use the shuffle method to create a random anagram of a string. Use the choice method to create a random anagram of a string. 12.
Write a program that gets a string from the user containing a potential telephone number. The program should print Valid if it decides the phone number is a real phone number, and Invalid otherwise.
A phone number is considered valid as long as it is written in the form _abc-def-hijk or 1-abc-def-hijk.
The dashes must be included, the phone number should contain_ only numbers and dashes, and the number of digits in each group must be correct.
Test your program with the output shown below. Enter a phone number: 1-301-447-5820 Valid Enter a phone number: 301-447-5820 Valid Enter a phone number: 301-4477-5820 Invalid Enter a phone number: 3X1-447-5820 Invalid Enter a phone number: 3014475820 Invalid 13.
Let L be a list of strings.
Write list comprehensions that create new lists from L for each of the following. (a) A list that consists of the strings of s with their first characters removed (b) A list of the lengths of the strings of s (c) A list that consists of only those strings of s that are at least three characters long 14.
Use a list comprehension to produce a list that consists of all palindromic numbers between 100 and 1000. 15.
Use a list comprehension to create the list below, which consists of ones separated by increasingly many zeroes.
The last two ones in the list should be separated by ten zeroes. [1,1,0,1,0,0,1,0,0,0,1,0,0,0,0,1,....] 16. Let L=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47].
Use a list comprehension to produce a list of the gaps between consecutive entries in L. Then find the maximum gap size and the percentage of gaps that have size 2. 17.
Write a program that finds the average of all of the entries in a 4 4 list of integers. _×_ 18. Write a program that creates a 10 10 list of random integers between 1 and 100.
Then do the _×_ following: (a) Print the list. (b) Find the largest value in the third row. (c) Find the smallest value in the sixth column. ----- 74 _CHAPTER 8. MORE WITH LISTS_ 19.
Write a program that creates and prints an 8 8 list whose entries alternate between 1 and 2 _×_ in a checkerboard pattern, starting with 1 in the upper left corner. 20.
Write a program that checks to see if a 4 4 list is a magic square. In a magic square, every _×_ row, column, and the two diagonals add up to the same value. 21.
Write a program that asks the user to enter a length. The program should ask them what unit the length is in and what unit they would like to convert it to.
The possible units are inches, yards, miles, millimeters, centimeters, meters, and kilometers.
While this can be done with 25 if statements, it is shorter and easier to add on to if you use a two-dimensional list of conversions, so please use lists for this problem. 22.
The following is useful as part of a program to play Battleship. Suppose you have a 5 5 list _×_ that consists of zeroes and ones. Ask the user to enter a row and a column.
If the entry in the list at that row and column is a one, the program should print Hit and otherwise it should print Miss. 23. This exercise is useful in creating a Memory game.
Randomly generate a 6 6 list of assorted _×_ characters such that there are exactly two of each character. An example is shown below. @ 5 # A A ! 5 0 b @ $ z $ N x !
N z 0 - + # b : - : + c c x 24. The following is useful in implementing computer players in a number of different games. Write a program that creates a 5 5 list consisting of zeroes and ones.
Your program should _×_ then pick a random location in the list that contains a zero and change it to a one. If all the entries are one, the program should say so.
[Hint: one way to do this is to create a new list whose items are the coordinates of all the ones in the list and use the choice method to randomly select one.
Use a two-element list to represent a set of coordinates.] 25. Here is an old puzzle question you can solve with a computer program.
There is only one five-digit number n that is such that every one of the following ten numbers shares exactly one digit in common in the same position as n.
Find n. 01265,12171,23257,34548,45970,56236,67324,78084,89872,99414 26. We usually refer to the entries of a two-dimensional list by their row and column, like below on the left.
Another way is shown below on the right. (0,0) (0,1) (0,2) 0 1 2 (1,0) (1,1) (1,2) 3 4 5 (2,0) (2,1) (2,2) 6 7 8 (a) Write some code that translates from the left representation to the right one.
The // and % operators will be useful.
Be sure your code works for arrays of any size. (b) Write some code that translates from the right representation to the left one. ----- ### Chapter 9 ## While loops We have already learned about for loops, which allow us to repeat things a specified number of times.
Sometimes, though, we need to repeat something, but we don’t know ahead of time exactly how many times it has to be repeated.
For instance, a game of Tic-tac-toe keeps going until someone wins or there are no more moves to be made, so the number of turns will vary from game to game. This is a situation that would call for a while loop. ###### 9.1 Examples **Example 1** Let’s go back to the first program we wrote back in Section 1.3, the tem...
One annoying thing about it is that the user has to restart the program for every new temperature. A while loop will allow the user to repeatedly enter temperatures.
A simple way for the user to indicate that they are done is to have them enter a nonsense temperature like 1000 (which _−_ is below absolute 0).
This is done below: temp = 0 **while temp!=-1000:** temp = eval(input('Enter a temperature (-1000 to quit): ')) **print('In Fahrenheit that is', 9/5*temp+32)** Look at the while statement first.
It says that we will keep looping, that is, keep getting and converting temperatures, as long as the temperature entered is not 1000. As soon as 1000 is _−_ _−_ entered, the while loop stops.
Tracing through, the program first compares temp to 1000. If temp _−_ is not 1000, then the program asks for a temperature and converts it.
The program then loops _−_ back up and again compares temp to 1000.
If temp is not 1000, the program will ask for another _−_ _−_ temperature, convert it, and then loop back up again and do another comparison.
It continues this process until the user enters 1000. _−_ We need the line temp=0 at the start, as without it, we would get a name error. The program would 75 |ter.
One annoying thing about it is that the user has to restart the program for every new tem- ature. A while loop will allow the user to repeatedly enter temperatures.
A simple way for the r to indicate that they are done is to have them enter a nonsense temperature like −1000 (which elow absolute 0).
This is done below:|Col2| |---|---| ||| |temp = 0 while temp!=-1000: temp = eval(input('Enter a temperature (-1000 to quit): ')) print('In Fahrenheit that is', 9/5*temp+32)|| ----- 76 _CHAPTER 9.
WHILE LOOPS_ get to the while statement, try to see if temp is not equal to 1000 and run into a problem because _−_ temp doesn’t yet exist. To take care of this, we just declare temp equal to 0.
There is nothing special about the value 0 here. We could set it to anything except 1000.
(Setting it to 1000 would cause _−_ _−_ the condition on the while loop to be false right from the start and the loop would never run.) Note that is natural to think of the while loop as continuing looping until the user enters -1000. However, when we construct the condition, instead of thinking about when to stop loo...
The difference is that the indented statements in an if block will only be executed once, whereas the indented statements in a while loop are repeatedly executed. **Example 2** One problem with the previous program is that when the user enters in 1000 to _−_ quit, the program still converts the value 1000 and doesn’t ...
A nicer way to do the program is shown below. temp = 0 **while temp!=-1000:** temp = eval(input('Enter a temperature (-1000 to quit): ')) **if temp!=-1000:** **print('In Fahrenheit that is', 9/5*temp+32)** **else:** **print('Bye!')** **Example 3** When first met if statements in Section 4.1, we wrote a program th...
The problem with that program is that the player only gets one guess.
We can, in a sense, replace the if statement in that program with a while loop to create a program that allows the user to keep guessing until they get it right. **from random import randint** secret_num = randint(1,10) guess = 0 **while guess != secret_num:** guess = eval(input('Guess the secret number: ')) **print...
In this case, the loop consists of one statement, the input statement, and so the program will keep asking the user for a guess until their guess is correct.
We require the line guess=0 prior to the while loop so that the first time the program reaches the loop, there is something in guess for the program to use in the comparison.
The exact value of guess doesn’t really matter at this point. We just want something that is guaranteed to be different than secret_num.
When the user finally guesses the right answer, the loop ends and program control moves to the print statement after the loop, which prints a congratulatory message to the player. |ample 2 One problem with the previous program is that when the user enters in −1000 to t, the program still converts the value −1000 and d...
A nicer way to do the program is shown below.|Col2| |---|---| ||| |temp = 0 while temp!=-1000: temp = eval(input('Enter a temperature (-1000 to quit): ')) if temp!=-1000: print('In Fahrenheit that is', 9/5*temp+32) else: print('Bye!')|| |ample 3 When first met if statements in Section 4.1, we wrote a program that play...
The problem with that program is that the player only gets one ess.
We can, in a sense, replace the if statement in that program with a while loop to create a gram that allows the user to keep guessing until they get it right.|Col2| |---|---| ||| |from random import randint secret_num = randint(1,10) guess = 0 while guess != secret_num: guess = eval(input('Guess the secret number: ')) ...
EXAMPLES_ 77 **Example 4** We can use a while loop to mimic a for loop, as shown below.
Both loops have the exact same effect. **for i in range(10):** i=0 **print(i)** **while i<10:** **print(i)** i=i+1 Remember that the for loop starts with the loop variable i equal to 0 and ends with it equal to 9. To use a while loop to mimic the for loop, we have to manually create our own loop variable i.
We start by setting it to 0.
In the while loop we have the same print statement as in the for loop, but we have another statement, i=i+1, to manually increase the loop variable, something that the for loop does automatically. **Example 5** Below is our old friend that converts from Fahrenheit to Celsius. temp = eval(input('Enter a temperature in...
The program below takes absolute_ zero into account: temp = eval(input('Enter a temperature in Celsius: ')) **if temp<-273.15:** **print('That temperature is not possible.'))** **else:** **print('In Fahrenheit, that is', 9/5*temp+32)** One way to improve this is to allow the user to keep reentering the temperature...
You may have experienced something similar using an online form to enter a phone number or a credit card number. If you enter an invalid number, you are told to reenter it.
In the code below, the while loop acts very similarly to the if statement in the previous example. temp = eval(input('Enter a temperature in Celsius: ')) **while temp<-273.15:** temp = eval(input('Impossible.
Enter a valid temperature: ')) **print('In Fahrenheit, that is', 9/5*temp+32)** Note that we do not need an else statement here, like we had with the if statement..
The condition on the while loop guarantees that we will only get to the print statement once the user enters a valid temperature.
Until that point, the program will be stuck in the loop, continually asking the user for a new temperature. **Example 6** As mentioned before, it is a valuable skill is to be able to read code.
One way to do so is to pretend to be the Python interpreter and go through the code line by line. Let’s try it with the |ample 4 We can use a while loop to mimic a for loop, as shown below.
Both loops have the ct same effect.|Col2| |---|---| ||| |for i in range(10): i=0 print(i) while i<10: print(i) i=i+1|| |ample 5 Below is our old friend that converts from Fahrenheit to Celsius.|Col2| |---|---| ||| |temp = eval(input('Enter a temperature in Celsius: ')) print('In Fahrenheit, that is', 9/5*temp+32)|| |...
e smallest possible temperature is absolute zero, -273.15 ◦C.
The program below takes absolute o into account:|Col2| |---|---| ||| |temp = eval(input('Enter a temperature in Celsius: ')) if temp<-273.15: print('That temperature is not possible.')) else: print('In Fahrenheit, that is', 9/5*temp+32)|| |e way to improve this is to allow the user to keep reentering the temperature u...
You may have experienced something similar using an online form to enter a phone mber or a credit card number. If you enter an invalid number, you are told to reenter it.
In the e below, the while loop acts very similarly to the if statement in the previous example.|Col2| |---|---| ||| |temp = eval(input('Enter a temperature in Celsius: ')) while temp<-273.15: temp = eval(input('Impossible.
Enter a valid temperature: ')) print('In Fahrenheit, that is', 9/5*temp+32)|| ----- 78 _CHAPTER 9.