• No results found

Exercises ListsLists

In document OO Programming in Python (Page 100-107)

Getting Started in Python

2.10 Case Study: Strings and Lists

2.11.3 Exercises ListsLists

Practice 2.1: Suppose the listastronautshas the value

['Yuri Gagarin','John Glenn','Neal Armstrong']

Give a single statement that adds 'Alan Shepard' between 'Yuri Gagarin' and 'John Glenn'.

Practice 2.2: Write a program that takes a list of strings namedpeopleand rearranges that list into reverse alphabetical order.

Practice 2.3: Write a statement that takes a list named houses and creates a new list someHouses containing every other house starting with the second (i.e., the sec-ond, fourth, sixth and so on).

Practice 2.4: Explain how to userangeto create a list with contents[2, 4, 6, 8]. Exercise 2.5: Assume that we have a list initialized as

fruits = ['orange','banana','grape','lime','strawberry'] Give a single command that replaces the occurrence of 'lime' with the string 'kiwi'.

Exercise 2.6: Give a series of statements that determine and print the string that comes second, in alphabetical order, from an initially unordered listfriends.

Exercise 2.7: Repeat Exercise 2.6, ensuring that the original list remains unchanged.

Exercise 2.8: The commandgroceries.append('milk')adds the element to the end of the list. Explain how to implement this action using theinsertmethod rather than theappendmethod.

Exercise 2.9: What is the result of the commandrange(13, 40, 5)?

Exercise 2.10: Explain how to use the range command to create a list with contents [8, 5, 2].

Exercise 2.11: Suppose thatnumbersis a list of values. Give a command or sequence of commands that outputs the median value from that list.

Exercise 2.12: Assume thatgroceriesis a list and that you have been told that 'milk' occurs five times on the list. Give a command or sequence of commands that removes the second occurrence of 'milk' while leaving the rest of the list intact.

Exercise 2.13: Assume that the identifierstuffreferences a list. Give an expression that represents the number of times the first item of this list occurs elsewhere on the list.

Strings

Practice 2.14: Consider the string defined as

example ='This is a test. This is only a test.' (a) Give the type and value of the expressionexample[12]. (b) Give the type and value of the expressionexample[6:12]. (c) Give the type and value of the expressionexample.count('is'). (d) Give the type and value of the expressionexample.index('a'). (e) Give the type and value of the expressionexample.index('is', 6).

(f) Give the type and value of the expressionexample.split('a').

Practice 2.15: Write an expression that isTrueifstringAandstringBare equivalent to each other in a case-insensitive manner.

Practice 2.16: Give an expression that is equal to the number of times the letter b occurs in the stringsong, including both uppercase and lowercase occurrences.

Practice 2.17: Assume thatpersonis a string of the form 'firstName lastName'.

Give a command or series of commands that results in the corresponding string 'lastName, firstName'.

Practice 2.18: Consider the following code fragment:

message ='Hello, my name is Frank' start = message[ :18]

name = message[18: ] letters = list(name) letters.remove('F') letters.sort( ) letters[1] ='N' name =''.join(letters)

name = name.replace('r','.') print start + name.capitalize( )

What is the output of the print statement?

Exercise 2.19: Write an expression that is Trueprecisely whenstringAis a capitalized version ofstringB.

Exercise 2.20: Assign identifiernumVowelsto the number of vowels in the given string poem.

Exercise 2.21: Assume thatfruitsis a list containing strings representing the names of var-ious fruits. Give a command or sequence of commands that produces a single string dietcontaining all of the fruits from the list, alphabetized and with spaces and a plus sign between each fruit. As an example, if the list of fruits happened to be

fruit = ['lime','apple','grape','cherry','orange','banana'] the resulting diet should have value

'apple + banana + cherry + grape + lime + orange' Exercise 2.22: Assume thatpersonis a string of the general form

'firstName middleName lastName'.

Give a command or series of commands that results in the creation of the corre-sponding string 'firstName middleInitial. lastname'. For example, ifperson ='Elmer Joseph Fudd', the result should be 'Elmer J. Fudd'.

Exercise 2.23: Give a code fragment that converts a general date string from the format '07/13/2007'into the associated format '13 July 2007'.

Expressions

Practice 2.24: Give the type and value of each expression.

(a) 23 + 8 (j) 'Python'.islower( )

(b) 3.5−1.1 (k) 'hocuspocus'.split('o')

(c) 2 * 3.1 (l) 'A'=='a'

(d) 17 / 5.0 (m) range(10,20)[3]

(e) 17 // 5 (n) len(range(10))

(f) 2 + 6.4 / 2 (o) 'expression'[2:7]

(g) 4 >= 6 (p) len('hello'[1:4])

(h) 3 *'12' (q) 3 + 4 == 7 and 1 + 1 != 4 (i) 'a'+'b'* 3 (r) True or (True and False)

Practice 2.25: Assume thatrrepresents the radius of a circle. Give an expression for the area of that circle.

Practice 2.26: An error occurs when evaluating each of the following expressions. Give the official type of error, as reported by the interpreter, and explain in your own words the precise reason for the error.

(a) 'hello'*'goodbye' (b) ' + '.join(range(10)) (c) range(10).split(',') (d) range(10).reverse( )[3]

(e) len(range(10).pop( ))

Exercise 2.27: Give the type and value of each expression.

(a) 3−8 (j) 'Python'.lower( )

(b) 8−1.5 (k) 'computer'<'science'

(c) 17 % 5 (l) 3 > 7 or 2 < 1

(d) 15.5 // 4.1 (m) False and (False or True) (e) 3 * 2 + 4 * 5 (n) range(10,20).pop( )

(f) 4−2 + 5 // 32 (o) len(range(10,20,4))

(g) 4 > 4 (p) [5][0]

(h) str(12 + 34) (q) 'sample'[1:4]

(i) ('a'+'b') * 3 (r) 'sample'[1:4:2]

Exercise 2.28: An error occurs when evaluating each of the following expressions. Give the official type of error, as reported by the interpreter, and explain in your own words the precise reason for the error.

(a) ['Do','Re','Mi'].join('-') (b) 'High'+ 5

(c) ['Do','Re','Mi'].insert('Fa') (d) 'hello'.remove('a')

(e) list('hello').remove('a')

Exercise 2.29: Draw an evaluation tree for the following statement:

alternate = monthNames[int(month)1] +' '+ day +', '+ year

User input/output

Practice 2.30: Write a short program that asks the user to enter his or her name, and says hello. For example,

What is your name? Frank Hello Frank!

Practice 2.31: Write a program that asks the user to enter two integers (separated by a space) and outputs the sum. For example,

Enter two integers: 5 16 Their sum is 21.

Exercise 2.32: Write a code fragment that prompts the user to enter an arbitrary number of values separated by commas and prints out the average of the numbers. The out-put should be a floating-point number. For example,

Enter some numbers separated by commas: 5, 18, 14 The average is 12.33

Projects

Exercise 2.33: Write a program that asks the user to enter a temperature in Fahrenheit and reports the equivalent temperature in Celsius. You may use the formula c=

5

9( f − 32) for doing the conversion. A sample session might appear as follows:

Enter a temperature in Fahrenheit: 85

85 Fahrenheit is equivalent to 29.4444 Celsius.

Exercise 2.34: The Body Mass Index is a screening measure meant to approximate a per-son’s body fat based upon his or her height and weight. Let W represent a weight (measured in pounds), and let H represent a height (measured in inches). Then the index is calculated according to the formula BMI= 703 ·W /H2.

Write a program that asks the user for their height and weight and reports the BMI. The user should enter the height in a format such as 5'8" to signify 5 feet 8 inches. A sample session might appear as follows:

What is your height (e.g., 5'8"): 5'10"

What is your weight (in pounds): 140 Your BMI is 20.0857.

(The normal range is listed as 18.5 to 24.9, according to the Department of Health and Human Services.)

Exercise 2.35: Write a program that asks the user to enter the name of a month and prints out the birthstone for that month. A sample session might appear as

Enter a month: April

April's birthstone is Diamond.

As part of your program, you may make use of the following two lists:

monthNames = ['January','February','March','April', 'May','June','July','August',

'September','October','November','December'] birthstones = ['Garnet','Amethyst','Aquamarine','Diamond',

'Emerald','Pearl','Ruby','Peridot', 'Sapphire','Opal','Topaz','Turquoise']

Exercise 2.36: Write a program that inputs a date and outputs how many days into the year it is. For example, May 5 is the 125th day of the year. (Do not worry about leap year.)

Exercise 2.37: DNA can be modeled as a string of characters using the alphabet: A, C, G, and T. One form of DNA mutation occurs when a substring of the DNA is reversed during the replication process. Usually, such a reversal occurs between what are termed inverted pairs. For example, if the pattern TGAA is later followed by the inverted pattern AAGT, it is possible that the slice of DNA delimited by those patterns

could be inverted and reattached, since the bonds at each end will be locally the same.

An example is shown here.

TGAATTACAAGT TGAACATTAAGT

Design a program that works as follows. It should ask the user for an original DNA string as well as the particular pattern that is inverted. It should then locate the leftmost occurrence of that pattern, and the next subsequent occurrence of the inverted pattern. The output should be the mutated DNA, with the segment between the inverted pair reversed. An example session might appear as follows:

Enter a DNA sequence: CGATTGAACATTAAGTCCAATT

Enter the pattern: TGAA

Mutated DNA sequence: CGATTGAATTACAAGTCCAATT

Note: the challenge of reversing a string is discussed in For the Guru on page 55.

C H A P T E R 3

In document OO Programming in Python (Page 100-107)