• Home
  • Textbooks
  • Introduction to Programming Using Python
  • Lists

Introduction to Programming Using Python

Y. Daniel Liang

Chapter 10

Lists - all with Video Answers

Educators

+ 5 more educators

Chapter Questions

01:54

Problem 1

(Assign grades) Write a program that reads a list of scores and then assigns grades based on the following scheme:
The grade is A if score is $>=$ best -10
The grade is $\mathrm{B}$ if score is $>=$ best -20
The grade is $\mathrm{C}$ if score is $>=\mathrm{best}-30$
The grade is $\mathrm{D}$ if score is $>=$ best -40
The grade is $\mathrm{F}$ otherwise.
Here is a sample run:
Enter scores: 40 55 70 58
Student 0 score is 40 and grade is C
Student 1 score is 55 and grade is B
Student 2 score is 70 and grade is A
Student 3 score is 58 and grade is B

Alexander Cheng
Alexander Cheng
Numerade Educator
04:38

Problem 2

(Reverse the numbers entered) Write a program that reads a list of integers and displays them in the reverse order in which they were read.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
07:35

Problem 3

(Count occurrence of numbers) Write a program that reads some integers between 1 and 100 and counts the occurrences of each. Here is a sample run of the program:
Enter integers between 1 and 100: 2 5 6 5 4 3 23 43 2
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
Note that if a number occurs more than one time, the plural word “times” is used in the output.

Mitchell Cutler
Mitchell Cutler
Numerade Educator
02:23

Problem 4

(Analyze scores) Write a program that reads an unspecified number of scores and determines how many scores are above or equal to the average and how many scores are below the average. Assume the input numbers are separated by one space in one line.

Ajay Singhal
Ajay Singhal
Numerade Educator
04:52

Problem 5

(Print distinct numbers) Write a program that reads in numbers separated by a space in one line and displays distinct numbers (i.e., if a number appears multiple times, it is displayed only once). (Hint: Read all the numbers and store them in list1. Create a new list list2. Add a number in list1 to list2. If the number is already in the list, ignore it.) Here is the sample run of the program:
Enter ten numbers:
The distinct numbers are: 1 2 3 6 4 5

Mitchell Cutler
Mitchell Cutler
Numerade Educator
02:12

Problem 6

(Revise Listing 5.13, PrimeNumber.py) Listing 5.13 determines whether a number n is prime by checking whether $2,3,4,5,6, \ldots, n / 2$ is a divisor for n. If a divisor is found, $n$ is not prime. A more efficient approach is to check whether any of the prime numbers less than or equal to $\sqrt{n}$ can divide n evenly. If not, $n$ is prime. Rewrite Listing 5.13 to display the first 50 prime numbers using this approach. You need to use a list to store the prime numbers and later use them to check whether they are possible divisors for $n$.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
05:46

Problem 7

(Count single digits) Write a program that generates 1,000 random integers between 0 and 9 and displays the count for each number. (Hint: Use a list of ten integers, say counts, to store the counts for the number of 0 s, 1 s $, \ldots, 9$ s.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
03:23

Problem 8

(Find the index of the smallest element) Write a function that returns the index of the smallest element in a list of integers. If the number of such elements is greater than $1,$ return the smallest index. Use the following header:
def indexofSmal lestE7ement(Tst):
Write a test program that prompts the user to enter a list of numbers, invokes this function to return the index of the smallest element, and displays the index.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
03:16

Problem 9

(Statistics: compute deviation) Exercise 5.46 computes the standard deviation of numbers. This exercise uses a different but equivalent formula to compute the standard deviation of n numbers.
\[\text {mean}=\frac{\sum_{i=1}^{n} x_{i}}{n}=\frac{x_{1}+x_{2}+\ldots+x_{n}}{n} \text { deviation }=\sqrt{\frac{\sum_{i=1}^{n}\left(x_{i}-\text {mean}\right)^{2}}{n-1}}\]
To compute the standard deviation with this formula, you have to store the individual numbers using a list, so that they can be used after the mean is obtained. Your program should contain the following functions:
$\#$ Compute the standard deviation of values def deviation(x):
$\#$ Compute the mean of a 7 ist of values def mean $(x):$
Write a test program that prompts the user to enter a list of numbers and displays the mean and standard deviation, as shown in the following sample run:
Enter numbers: $\begin{array}{lllllllll}1.9 & 2.5 & 3.7 & 2 & 1 & 6 & 3 & 4 & 5 & 2\end{array}$
The mean is 3.11
The standard deviation is 1.55738

MS
Malcom Smith
Numerade Educator
03:36

Problem 10

(Reverse a list) The reverse function in Section 10.8 reverses a list by copying it to a new list. Rewrite the function that reverses the list passed in the argument and returns this list. Write a test program that prompts the user to enter a list of numbers, invokes the function to reverse the numbers, and displays the numbers.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
06:48

Problem 11

(Random number chooser) You can shuffle a list using random . shuffle( 1 st). Write your own function without using random . shuff 7 e $(7 \text { st })$ to shuffle a list and return the list. Use the following function header:
def shuffle( $1 \text { st }):$
Write a test program that prompts the user to enter a list of numbers, invokes the function to shuffle the numbers, and displays the numbers.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
03:45

Problem 12

(Compute $G C D$ ) Write a function that returns the greatest common divisor (GCD) of integers in a list. Use the following function header:
def gcd(numbers):
Write a test program that prompts the user to enter five numbers, invokes the function to find the GCD of these numbers, and displays the GCD.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
03:36

Problem 13

(Eliminate duplicates) Write a function that returns a new list by eliminating the duplicate values in the list. Use the following function header:
def eliminateDup1 icates( $7 \text { st }):$
Write a test program that reads in a list of integers, invokes the function, and displays the result. Here is the sample run of the program:
Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 123645

Tarandeep Singh
Tarandeep Singh
Numerade Educator
03:04

Problem 14

(Revise selection sort) In Section $10.11 .1,$ you used selection sort to sort a list. The selection-sort function repeatedly finds the smallest number in the current list and swaps it with the first one. Rewrite this program by finding the largest number and swapping it with the last one. Write a test program that reads in ten numbers, invokes the function, and displays the sorted numbers.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
05:26

Problem 15

(Sorted?) Write the following function that returns true if the list is already sorted in increasing order:
def isSorted(Tst):
Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. Here is a sample run:
Enter Tist: 1 1 3 4 4 5 7 9 10 30 11
The 7 ist is not sorted
Enter 7 ist: 1 1 3 4 4 5 7 9 10 30
The 7 ist is already sorted

Tarandeep Singh
Tarandeep Singh
Numerade Educator
10:41

Problem 16

(Bubble sort) Write a sort function that uses the bubble-sort algorithm. The bubble-sort algorithm makes several passes through the list. On each pass, successive neighboring pairs are compared. If a pair is in decreasing order, its values are swapped; otherwise, the values remain unchanged. The technique is called a bubble sort or sinking sort because the smaller values gradually “bubble” their way to the top and the larger values “sink” to the bottom. Write a test program that reads in ten numbers, invokes the function, and displays the sorted numbers.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
02:37

Problem 17

(Anagrams) Write a function that checks whether two words are anagrams. Two words are anagrams if they contain the same letters. For example, silent and 7 isten are anagrams. The header of the function is:
def isAnagram(s1, s2):
(Hint: Obtain two lists for the two strings. Sort the lists and check if two lists are identical.)
Write a test program that prompts the user to enter two strings and, if they are anagrams, displays is an anagram; otherwise, it displays is not an anagram.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
05:23

Problem 18

(Game: Eight Queens) The classic Eight Queens puzzle is to place eight queens on a chessboard such that no two queens can attack each other (i.e., no two queens are in the same row, same column, or same diagonal). There are many possible solutions. Write a program that displays one such solution. A sample output is shown below:

Morgan Cheatham
Morgan Cheatham
Numerade Educator
05:10

Problem 19

(Game: bean machine) The bean machine, also known as a quincunx or the Galton box, is a device for statistics experiments named after English scientist Sir Francis Galton. It consists of an upright board with evenly spaced nails (or pegs ) in a triangular pattern, as shown in Figure 10.15 Balls are dropped from the opening of the board. Every time a ball hits a nail, it has a $50 \%$ chance of falling to the left or to the right. The piles of balls are accumulated in the slots at the bottom of the board.
Each ball takes a random path and falls into a slot.
Write a program that simulates the bean machine. Your program should prompt the user to enter the number of the balls and the number of the slots in the machine. Simulate the falling of each ball by printing its path. For example the path for the ball in Figure 10.15 b is LLRRLLR and the path for the ball in Figure $10.15 \mathrm{c}$ is RLRRLRR. Display the final buildup of the balls in the slots in a histogram. Here is a sample run of the program:
Enter the number of balls to drop: 5
Enter the number of slots in the bean machine: 7
LRLRLRR
RRLLLRR
LLRLLRR
RRLLLLL
LRLRRLR
0
0
000
(Hint: Create a list named stots. Each element in slots stores the number of balls in a slot. Each ball falls into a slot via a path. The number of $R$ s in a path is the position of the slot where the ball falls. For example, for the path LRLRLRR, the ball falls into stots[4], and for the path is RRLLLLL, the ball falls into s\rceil ots $[2] .)$

Morgan Cheatham
Morgan Cheatham
Numerade Educator
04:42

Problem 20

(Game: multiple Eight Queens solutions) Exercise 10.18 has you find one solution for the Eight Queens puzzle. Write a program to count all possible solutions for the Eight Queens problem and display all the solutions.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
03:50

Problem 21

(Game: locker puzzle) A school has 100 lockers and 100 students. All lockers are closed on the first day of school. As the students enter, the first student, denoted S1, opens every locker. Then the second student, S2, begins with the second locker, denoted $\mathrm{L} 2,$ and closes every other locker. Student $\mathrm{S} 3$ begins with the third locker and changes every third locker (closes it if it was open, and opens it if it was closed). Student S4 begins with locker L4 and changes every fourth locker. Student S5 starts with L5 and changes every fifth locker, and so on, until student S100 changes L100. After all the students have passed through the building and changed the lockers, which lockers are open? Write a program to find your answer. (Hint: Use a list of 100 Boolean elements, each of which indicates whether a locker is open (True) or closed (False). Initially, all lockers are closed.)

Morgan Cheatham
Morgan Cheatham
Numerade Educator
03:30

Problem 22

(Simulation: coupon collector's problem) Coupon Collector is a classic statistics problem with many practical applications. The problem is to pick objects from a set of objects repeatedly and find out how many picks are needed for all the objects to be picked at least once. A variation of the problem is to pick cards from a shuffled deck of 52 cards repeatedly and find out how many picks are needed before you see one of each suit. Assume a picked card is placed back in the deck before picking another. Write a program to simulate the number of picks needed to get four cards, one from each suit and display the four cards picked (it is possible a card may be picked twice). Here is a sample run of the program:
Queen of Spades
5 of $\mathrm{Clubs}$
Queen of Hearts
4 of Diamonds
Number of picks: 12

Morgan Cheatham
Morgan Cheatham
Numerade Educator
15:41

Problem 23

(Algebra: solve quadratic equations) Write a function for solving a quadratic equation using the following header:
def solveQuadratic(eqn, roots):
The coefficients of a quadratic equation $a x^{2}+b x+c=0$ are passed to the list eqn and the noncomplex roots are stored in roots. The function returns the number of roots. See Programming Exercise 4.1 on how to solve a quadratic equation.
Write a program that prompts the user to enter values for $a, b,$ and $c$ and displays the number of roots and all noncomplex roots.

Samuel Goyette
Samuel Goyette
Numerade Educator
06:30

Problem 24

(Math: combinations) Write a program that prompts the user to enter 10 integers and displays all the combinations of picking two numbers from the 10 .

Tarandeep Singh
Tarandeep Singh
Numerade Educator
04:48

Problem 25

(Game: pick four cards) Write a program that picks four cards from a deck of 52 cards and computes their sum. An ace, king, queen, and jack represent 1,13,12 and $11,$ respectively. Your program should display the number of picks that yield the sum of 24.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
03:08

Problem 26

(Merge two sorted lists) Write the following function that merges two sorted lists into a new sorted list:
def merge( $7 \text { ist1, } 7 \text { ist2 }):$
Implement the function in a way that takes 7 en $(7 \text { ist } 1)+7$ en $(7 \text { ist2 })$ comparisons. Write a test program that prompts the user to enter two sorted lists and displays the merged list. Here is a sample run:
Enter Tist1: 1 5 16 61 111
Enter 7 ist2: 2 4 5 6
The merged 1 ist is 1 2 4 5 5 6 16 61 111

Morgan Cheatham
Morgan Cheatham
Numerade Educator
08:24

Problem 27

(Pattern recognition: four consecutive equal numbers) Write the following function that tests whether the list has four consecutive numbers with the same value:
def i sConsecutiveFour(values):
Write a test program that prompts the user to enter a series of integers and reports whether the series contains four consecutive numbers with the same value.

Tarandeep Singh
Tarandeep Singh
Numerade Educator
02:33

Problem 28

(Partition of a list) Write the following function that partitions the list using the first element, called a pivot:
def partition(7st):
After the partition, the elements in the list are rearranged so that all the elements before the pivot are less than or equal to the pivot and the element after the pivot are greater than the pivot. The function also returns the index where the pivot is located in the new list. For example, suppose the list is $[5,2,9,3,$ 6,8]$.$ After the partition, the list becomes $[3,2,5,9,6,8] .$ Implement the function in a way that takes 7 en $(7 s t)$ comparisons. Write a test program that prompts the user to enter a list and displays the list after the partition. Here is a sample run:
Enter a list: 10 1 5 16 61 9 11 1
After the partition, the 7 ist is 9 1 5 1 10 61 11 16

Patina Herring
Patina Herring
Numerade Educator
00:02

Problem 29

(Game: hangman) Write a hangman game that randomly generates a word and prompts the user to guess one letter at a time, as shown in the sample run. Each letter in the word is displayed as an asterisk. When the user makes a correct guess, the actual letter is then displayed. When the user finishes a word, display the number of misses and ask the user whether to continue playing. Create a list to store the words, as follows:
# Use any words you wish words $=[" \text { write" }, \text { "that", "program", } \dots]$
(Guess) Enter a Tetter in word $* * * * * *>p$
(Guess) Enter a Tetter in word pre*rrow $>p$ $p$ is already in the word (Guess) Enter a letter in word pre*rrin $>0$
(Guess) Enter a letter in word pro*r** > g (Guess) Enter a letter in word progr** > n $\mathrm{n}$ is not in the word
(Guess) Enter a letter in word progr** > $\mathrm{m}$
(Guess) Enter a letter in word progr*m $>a$
The word is program. You missed 1 time
Do you want to guess another word? Enter y or $n>$

Mariano Edutestprod
Mariano Edutestprod
Numerade Educator
01:24

Problem 30

(Culture: Chinese Zodiac) Simplify Listing 4.5, ChineseZodiac.py, using a list of strings to store the animals' names.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
06:30

Problem 31

(Occurrences of each digit in a string) Write a function that counts the occurrences of each digit in a string using the following header:
def count(s):
The function counts how many times a digit appears in the string. The return value is a list of ten elements, each of which holds the count for a digit. For example, after executing counts $=$ count $\left(^{\prime \prime} 12203 \mathrm{AB} 3^{\prime \prime}\right),$ counts [0] is 1 counts [1] is $1,$ counts [2] is $2,$ and counts [3] is 2
Write a test program that prompts the user to enter a string and displays the number of occurrences of each digit in the string. Here is a sample run of the
program:
Enter a string: 232534312
1 occurs 1 time
2 occurs 3 times
3 occurs 3 times
4 occurs 1 time
5 occurs 1 time

Tarandeep Singh
Tarandeep Singh
Numerade Educator
02:04

Problem 32

(Turtle: draw a line) Write the following function that draws a line from point $\mathrm{p} 1([\mathrm{x} 1, \mathrm{y} 1])$ to point $\mathrm{p} 2([\mathrm{x} 2, \mathrm{y} 2])$
$\#$ Draw a 7 ine def drawLine $(p 1, p 2)$

Patina Herring
Patina Herring
Numerade Educator
03:22

Problem 33

(Tkinter: draw histograms) Write a program that generates 1,000 lowercase letters randomly, counts the occurrence of each letter, and displays a histogram for the occurrences, as shown in Figure 10.16 a.
FIGURE I 0.16
(a) A histogram is drawn for the count of each letter
(b) Two buttons are added to control the ball speed.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
03:36

Problem 34

(Turtle: draw histograms) Rewrite the preceding program using Turtle.

Morgan Cheatham
Morgan Cheatham
Numerade Educator
02:55

Problem 35

(Tkinter: bouncing balls) Revise Listing 10.13 to add two buttons - Faster and Slower, as shown in Figure $10.16 \mathrm{b}$ -to speed up or slow down the ball
movements.

James Kiss
James Kiss
Numerade Educator
02:46

Problem 36

(Tkinter: linear search animation) Write a program that animates the linear search algorithm. Create a list that consists of 20 distinct numbers from 1 to 20 in a random order. The elements are displayed in a histogram, as shown in Figure $10.17 .$ You need to enter a search key in the text field. Clicking the Step button causes the program to perform one comparison in the algorithm and repaints the histogram with a bar indicating the search position. When the algorithm is finished, display a dialog box to inform the user. Clicking the Reset button creates a new random list for a new start.

James Kiss
James Kiss
Numerade Educator
03:30

Problem 37

(Tkinter: binary search animation) Write a program that animates the binary search algorithm. Create a list with the numbers from 1 to 20 in this order. The elements are displayed in a histogram, as shown in Figure $10.18 .$ You need to enter a search key in the text field. Clicking the Step button causes the program to perform one comparison in the algorithm. Use a light-gray color to paint the bars for the numbers in the current search range and use a red color to paint the bar indicating the middle number in the search range. When the algorithm is finished, display a dialog box to inform the user. Clicking the Reset button enables a new search to start. This button also makes the text field editable.

James Kiss
James Kiss
Numerade Educator
03:18

Problem 38

(Tkinter: selection-sort animation) Write a program that animates the selection-sort algorithm. Create a list that consists of 20 distinct numbers from 1 to 20 in a random order. The elements are displayed in a histogram, as shown in Figure 10.19 Clicking the Step button causes the program to perform an iteration of the outer loop in the algorithm and repaints the histogram for the new list. Color the last bar in the sorted sublist. When the algorithm is finished, display a dialog box to inform the user. Clicking the Reset button creates a new random list for a new start

James Kiss
James Kiss
Numerade Educator
03:15

Problem 39

(Tkinter: the 24 -point card game) The 24-point card game involves picking any four cards from 52 cards, as shown in Figure $10.20 .$ Note that the jokers are excluded. Each card represents a number. An ace, king, queen, and jack represent $1,13,12,$ and 11 respectively. Enter an expression that uses the four numbers from the four selected cards. Each card number can be used only once in each expression, and each card must be used. You can use the operators $(+,-, *, \text { and } /)$ and parentheses in the expression. The expression must evaluate to $24 .$ After entering the expression, click the Verify button to check whether the numbers in the expression are currently selected and whether the result of the expression is correct. Display the verification in a dialog box. You can click the Refresh button to get another set of four cards. Assume that images are stored in files named $1 .$ gif, $2 .$ gif, $\ldots, 52 .$ gif, in the order of spades, hearts, diamonds, and clubs. So, the first 13 images are for spades $1,2,3, \ldots,$ and 13.

James Kiss
James Kiss
Numerade Educator
03:04

Problem 40

(Tkinter: insertion-sort animation) Write a program that animates the insertion-sort algorithm. Create a list that consists of 20 distinct numbers from 1 to 20 in a random order. The elements are displayed in a histogram, as shown in Figure 10.21 Clicking the Step button causes the program to perform an iteration of the outer loop in the algorithm and repaints the histogram for the new list. Color the last bar in the sorted sublist. When the algorithm is finished, display a dialog box to inform the user. Clicking the Reset button creates a new random list for a new start.

James Kiss
James Kiss
Numerade Educator
03:27

Problem 41

(Display five circles) Write a program that displays five circles, as shown in Figure 10.22 a. Enable the user to drag each circle using the mouse, as shown in Figure $10.22 \mathrm{b}$.

James Kiss
James Kiss
Numerade Educator