Learn Exercises Python

29
Python Exercises for CSE 1310 December 3, 2010

Transcript of Learn Exercises Python

Page 1: Learn Exercises Python

Python Exercises for CSE 1310

December 3, 2010

Page 2: Learn Exercises Python

2

Page 3: Learn Exercises Python

Contents

1 Statements 5

2 Conditionals 7

3 Loops 9

4 Functions 11

5 Lists 13

6 Strings 15

7 File I/O 17

8 Dictionaries 19

9 Bugs 21

A Answers 25A.1 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25A.2 Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25A.3 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25A.4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26A.5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27A.6 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28A.7 File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28A.8 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

3

Page 4: Learn Exercises Python

CONTENTS CONTENTS

4

Page 5: Learn Exercises Python

Chapter 1

Statements

1. (added 8/26/2010) The program below calculates the area of a rectangle:

print "I will calculate the area of a rectangle for you."

sideA = input("Enter the length of one side:")

sideB = input("Enter the length of an adjacent side:")

area = sideA * sideB

print "The area is", area

Modify the program to add a third dimension, that is, find the area of a rectangularcuboid.

2. (added 8/30/2010) Write a program that prompts the user for a number and then usesit to evaluate the following mathematical function: f(x) = 3x2 + 5x − 6

3. (added 8/26/2010) Write a program that will prompt the user for a temperature inFahrenheit and then convert it to Celsius. You may recall that the formula is C =5 ∗ (F − 32)/9.

4. (added 8/26/2010) Run the program below, using both integers (e.g., 10) and non-integers (e.g., 13.89):

numerator = input(’What is the numerator? ’)

denominator = 4.0

print numerator, "/", denominator, "=", numerator/denominator

Notice that the variable denominator has a value of 4.0, not 4. Change the value to 4and run the program again. You should notice that when you provide an integer as thenumerator, you never get a non-integer answer, even when you should. Why is this?

5

Page 6: Learn Exercises Python

CHAPTER 1. STATEMENTS

6

Page 7: Learn Exercises Python

Chapter 2

Conditionals

1. (added 8/26/2010) Compare the two programs below. Do you expect them to producethe same output? Why?version 1:

x = 5

if x < 4:

print x, "is less than 4"

elif x < 6:

print x, "is less than 6"

elif x < 8:

print x, "is less than 8"

elif x < 10:

print x, "is less than 10"

else:

print x, "is greater than or equal to 10"

version 2:

x = 5

if x < 4:

print x, "is less than 4"

if x < 6:

print x, "is less than 6"

if x < 8:

print x, "is less than 8"

if x < 10:

print x, "is less than 10"

else:

7

Page 8: Learn Exercises Python

CHAPTER 2. CONDITIONALS

print x, "is greater than or equal to 10"

2. (added 8/29/2010) Modify the program in question 1.3 to state whether or not waterwould boil at the temperature given. Your output might look like this:

What is the temperature in Fahrenheit? 100

A temperature of 100 degrees Fahrenheit is 37 in Celsius

Water does not boil at this temperature (under typical conditions).

8

Page 9: Learn Exercises Python

Chapter 3

Loops

1. (added 8/26/2010) Write a program that picks a random integer in the range of 1 to100. It then prompts the user for a guess of the value, with hints of ’too high’ or’too low’ from the program. The program continues to run until the user guesses theinteger. To have the program choose a random integer in the range of 1 to 100, usethe statement

value = random.randint(1, 100)

2. (added 8/29/2010) Write a program that prompts the user for two positive integers,which we will call b and e. The program will calculate be. That is, the program willraise a positive integer to a positive integer power. Hint: think about how you wouldexplain to a first-grader what be means.

3. (added 8/30/2010) Write a program that prompts the user for two positive integers, aand b, and then sums the integers from a to b, inclusive. Output might look like this:

Enter a starting integer: 5

Enter a stopping integer: 15

The sum from 5 to 15 is 110

4. (added 8/30/2010) Write a program that prompts the user for two positive integers, aand b, and then counts the number of even integers in the range of a to b. Print theeven integers in this range. Output might look like this:

Enter a starting integer: 8

Enter a stopping integer: 19

8

10

12

14

9

Page 10: Learn Exercises Python

CHAPTER 3. LOOPS

16

18

There are 6 even integers between 8 and 19

10

Page 11: Learn Exercises Python

Chapter 4

Functions

1. (added 8/30/2010) Rewrite the program for question 3.4. This time, write a functionto determine the count of even integers. Therefore, the pseudocode for the main sectionof the program will be:

prompt user for starting and stopping values

call function to determine count of even integers (function returns count)

print count

2. (added 10/12/2010) The program below calls a function, swap(), that receives twonumbers, swaps the two numbers, and then returns them. Write swap().

### main ###

x = 99

y = 1000

print x, y

x, y = swap( x, y )

print x, y

3. (added 10/12/2010) Write a function that when given an integer, n, prints a pyramidn levels high from asterisks. Example:

how tall should the pyramid be? 5

*

* *

* * *

* * * *

* * * * *

how tall should the pyramid be? 10

11

Page 12: Learn Exercises Python

CHAPTER 4. FUNCTIONS

*

* *

* * *

* * * *

* * * * *

* * * * * *

* * * * * * *

* * * * * * * *

* * * * * * * * *

* * * * * * * * * *

12

Page 13: Learn Exercises Python

Chapter 5

Lists

Many of these ask that you write a function. If you are unsure of how to do that, try writingit without using a function. That is, put all of the code in the main body of the program.

1. (added 10/17/2010) Write a function that when given a 2-dimensional list will printthe list in its original shape. For example, if given the list

dataList = [ [ 1, 2, 3, 4] ,

[ 5, 6, 7, 8],

[ 9, 10, 11, 12] ]

the function will print

1 2 3 4

5 6 7 8

9 10 11 12

You can assume that all of the values in the list are integers of one or two digits each.

2. (added 10/12/2010) Rewrite the function in problem 4.2. This time, instead of re-turning two separate numbers, the function will return a list with the two numbers init.

3. (added 10/12/2010) Write a function that when given a 1-dimensional list will sumthe values in the list and return the sum.

4. (added 10/17/2010) Write a function that when given a 2-dimensional list will sumand print the values of each row. This can be done using for loops, but if you wishto use while loops you will need to know the number of rows and columns. For a2-dimensional list called aList, you can find the number of rows and columns usingthe code

13

Page 14: Learn Exercises Python

CHAPTER 5. LISTS

numRows = len( aList )

numCols = len( aList[0] )

5. (added 10/17/2010) Write a function that when given a 2-dimensional list will sumand print the values of each column.

6. (added 9/29/2010) Write your own version of Python’s range() function. The func-tion, myrange(), will be called using the form myrange(a, b) where a < b. If youwant more of a challenge, add a third parameter, c, that is the increment for the valuesin the list.

7. (added 10/17/2010) Write a function that when given two 1-dimensional lists of thesame length, add the elements in the same position and saves the results in anotherlist which the function returns.

8. (added 10/28/2010) Write a function that when given a two-dimensional list returnsthe row and column indices of the maximum value in the list. Your function shouldbe able to handle a list with any number of rows and columns. Remember that inPython, a function can return multiple values, for example

return rowIndex, colIndex

14

Page 15: Learn Exercises Python

Chapter 6

Strings

1. (added 10/28/2010) Write a function that will receive a string of comma-separatedwords and count how many of the words have more than five letters. The function willreturn the count when finished.

2. (added 10/28/2010) Write a function that receives a string that consists of any combi-nation of spaces, digits, uppercase or lowercase letters. The function should count thenumber of uppercase letters and return this count.

15

Page 16: Learn Exercises Python

CHAPTER 6. STRINGS

16

Page 17: Learn Exercises Python

Chapter 7

File I/O

1. (added 10/17/2010) Read a file, saving it to a list. Then print the file from this list.

2. (added 10/17/2010) Read a file in CSV format, swapping the columns as you printthem. For example, if each line consists of two numbers separated by a comma, printthe two numbers in reverse order. A first few lines of a sample file might be

1,3

5,9

6,8

3. (added 10/17/2010) Read a CSV file in which each line consists of numbers separatedby commas. Sum the numbers in the last column.

4. (added 10/17/2010) Read a CSV file in which each line consists of numbers separatedby commas. If all lines have the same quantity of numbers (e.g., three numbers perline), prompt the user for an integer, n, and then sum the numbers in column n.

5. (added 10/28/2010) Write a program that reads a file, numbers.txt, in which eachline consists of a single integer. The integers can be positive, negative, or zero. Theprogram should find the maximum value in the file and print it.

17

Page 18: Learn Exercises Python

CHAPTER 7. FILE I/O

18

Page 19: Learn Exercises Python

Chapter 8

Dictionaries

1. (added 11/1/2010) Create a dictionary with people’s names as keys and their ages asvalues and print each person’s name and age.

2. (added 11/1/2010) Modify the previous program to only print the names and ages ofpeople over 20 years old.

3. (added 11/1/2010) Modify the previous program to find the youngest person in thedictionary.

4. (added 11/1/2010) Store the names and ages in a CSV file and read in the file, creatinga dictionary from it.

5. (added 12/2/2010) We have the following data:

Name Age WeightTom 43 185John 50 170Susan 35 125

Store this data in a dictionary with the name as the key. Write a function that whengiven a dictionary of this form and either the word ”age” or ”weight” will print thename of the user with the largest age or weight (depending on the word passed). Forexample, the function call might look like this:

fx( data, "age" )

You can assume that age and weight will be the only two things stored for each name,but don’t make assumptions about the number of entries in the dictionary.

19

Page 20: Learn Exercises Python

CHAPTER 8. DICTIONARIES

20

Page 21: Learn Exercises Python

Chapter 9

Bugs

All of the programs below have logic errors.

1. (added 12/2/2010) The program below reads data01.csv and stores the entries in adictionary. When printing the dictionary, we get the following results:

{’dog’: ’200’, ’cat’: ’100’}

Why aren’t all of the lines from the file stored?

inFile = open("data01.csv", "r")

data = inFile.readlines()

inFile.close()

d = {}

for line in data :

animal, quantity = line.strip().split(’,’)

d[animal] = quantity

print d

# data01.csv

"""

cat,14

dog,58

cat,100

dog,200

"""

21

Page 22: Learn Exercises Python

CHAPTER 9. BUGS

2. (added 12/2/2010) The program below prints

The contents of the list are: 5 7 56 14 23

Why aren’t all of the list elements printed?

d = [99, 5, 7, 56, 14, 23]

print "The contents of the list are: " ,

i = 1

while i < 6 :

print d[i] ,

i += 1

3. (added 12/2/2010) The program prints

there are 1 even integers in the list

Why?

def even( data ) :

count = 0

for n in data :

if n % 2 == 0 :

count += 1

return count

### main ###

d = [8, 10, 7, 9, 4, 2]

print "there are %d even integers in the list" % even( d )

4. (added 12/3/2010) The program prints

the average is 2.00

22

Page 23: Learn Exercises Python

CHAPTER 9. BUGS

d = [1, 2, 3, 4]

sum = 0

i = 0

while i < 4 :

sum += d[i]

i += 1

print "the average is %3.2f" % (sum/4)

5. (added 12/3/2010) The program below produces the following output:

[4, 5, 6, 7]

[4, 5, 6, 7]

The function reverse() should reverse the list in place. Why doesn’t it?

def reverse( aList ) :

length = len(aList)

i = 0

while i < length :

temp = aList[i]

aList[i] = aList[length - 1 - i]

aList[length - 1 - i] = temp

i += 1

### main ###

d = [ 4, 5, 6, 7 ]

print d

reverse( d )

print d

6. (added 12/3/2010) The program should print the 4 × 4 multiplication table

1 2 3 4

2 4 6 8

3 6 9 12

4 8 12 16

the end

23

Page 24: Learn Exercises Python

CHAPTER 9. BUGS

but instead prints

1 2 3 4

the end

Why?

r = 1

c = 1

while r <= 4 :

while c <= 4 :

print "%2d" % (r * c) ,

c += 1

print

r += 1

print "the end"

24

Page 25: Learn Exercises Python

Appendix A

Answers

Answers to select problems.

A.1 Statements

A1.3 This is one possible implementation.

f = input(’What is the temperature in Fahrenheit? ’)

c = 5 * (f - 32) / 9

print "A temperature of", f, "degrees Fahrenheit is", c, "in Celsius"

A1.4 Division of integers in Python (and many other languages) uses integer division. Thatis, dividing an integer by an integer produces an integer. When the variable denominatorhad a value of 4.0, it was stored as a floating-point value (i.e., something that can storethe decimal part of a number). The result of dividing an integer by a floating-pointnumber is a floating-point number.

A.2 Conditionals

A.3 Loops

A3.1 Here is pseudocode for the solution:

generate random integer in the range 1 to 100

while guess not equal to random value

prompt the user for guess

25

Page 26: Learn Exercises Python

A.4. FUNCTIONS APPENDIX A. ANSWERS

if guess > random value

print ’too high’

else

print ’too low’

A3.3 start = input("Enter a starting integer: ")

stop = input("Enter a stopping integer: ")

count = start

sum = 0

while count <= stop :

sum = sum + count

count = count + 1

print "The sum from", start, "to", stop, "is", sum

A.4 Functions

A4.1 def evenCount(count, stop) :

sum = 0

while count <= stop :

if count%2 == 0 :

sum = sum + 1

print count

count = count + 1

return sum

start = input("Enter a starting integer: ")

stop = input("Enter a stopping integer: ")

total = evenCount(start, stop)

print "There are", total, "even integers between", start, "and", stop

26

Page 27: Learn Exercises Python

APPENDIX A. ANSWERS A.5. LISTS

A.5 Lists

A5.1 def printList( aList ) :

for row in aList :

for col in row :

print "%2d " % ( col ) ,

print

dataList = [ [ 1, 2, 3, 4] ,

[ 5, 6, 7, 8],

[ 9, 10, 11, 12] ]

printList( dataList )

A5.3 def sumList( aList ) :

sum = 0

for i in aList :

sum += i

return sum

A5.7 def addLists( aList, bList ) :

length = len( aList )

cList = []

i = 0

while i < length :

cList.append( aList[i] + bList[i] )

i += 1

return cList

#### main ####

a = [1, 2, 3]

b = [10, 20, 30]

d = [100, 200, 300, 400, 500]

e = [ 5, 4, 3, 2, 1]

print addLists(a, b)

print addLists(d, e)

27

Page 28: Learn Exercises Python

A.6. STRINGS APPENDIX A. ANSWERS

A.6 Strings

A6.1 def countCap( s ) :

count = 0

length = len( s )

i = 0

while i < length :

if ’A’ <= s[i] and s[i] <= ’Z’ :

print s[i]

count += 1

i += 1

return count

A.7 File I/O

A7.2 inFile = open("sample.csv", "r")

dataList = inFile.readlines()

inFile.close()

for line in dataList :

line = line.strip()

tokens = line.split(’,’)

print tokens[1], tokens[0]

A.8 Dictionaries

A8.5 def printMax( data, col ) :

if col == "age" :

index = 0

elif col == "weight" :

index = 1

maxVal = -1 # neither weight nor age can be less than zero

keys = data.keys()

for k in keys :

if data[k][index] > maxVal :

maxVal = data[k][index]

maxName = k

28

Page 29: Learn Exercises Python

APPENDIX A. ANSWERS A.8. DICTIONARIES

print "%s has the maximum %s" % (maxName, col)

### main ###

data = {"Tom" : [43, 185],

"John" : [50, 170],

"Susan" : [35, 125] }

printMax(data, "age")

printMax(data, "weight")

29