SOPH 303 The Digital World Term 3. January 28-May 3. 2013 Problem Set 3 (for Week 3) with test cases Last update: February 15, 2013 Due dates: • Problems: Cohort sessions: Following week: Monday 11:59pm for cohorts 1, 2, 5 and 7; Tuesday 11:59pm for cohorts 3, 4, and 6. • Problems: Homework: Same as for the cohort session problems. • Problems: Exercises: These are practice problems and will not be graded. You are encouraged to solve these to enhance your programming skills. Being able to solve these problems will likely help you prepare for the midterm examination. Objectives 1. Learn nested lists. 2. Learn how to create and use nested lists as tables. 3. Learn how to traverse sublists 4. Learn tuples 5. Understand recursion 6. Learn how to find roots of a polynomial using Newton’s method 7. Learn to use the Simpson’s method to find approximation of an integral. Note: Solve the programming problems listed below using the IDLE editor. Make sure you save your programs in files with suitably chosen names and in an newly created directory. In each problem find out a way to test the correctness of your program. After writing each program, test it, debug it if the program is incorrect, correct it, and repeat this process until you have a fully working program. Show your working program to one of the cohort instructors. Problems: Cohort sessions 1. Lists: review The following problems test your knowledge of lists in Python; no need to write a program for these but you can verify your answers by writing programs. (a) Specify the value of x[0] after the following code snippet. x =[1 ,2 ,3] x [0]=0 y=x y [0]=1 (b) Specify the value of x[0] after the following code snippet. x =[1 ,2 ,3] def f ( l ) : l [0]= ’a ’ f(x) (c) What is the value of a[0][0][0][0] after executing the following code snippet? Write ’E’ if there are any errors. x =[1 ,2 ,3] y =[ x ] a =[ y , x ] y [0][0] = (1 ,2) (d) Specify the values of expressions (a), (b), (c) and (d) in the following code. x =[1 ,2 ,3] y1 =[ x ,0] y2 = y1 [:] y2 [0][0]=0 y2 [1]=1 y1 [0][0] # ( a ) y1 [1] # ( b ) y2 [0][0] # ( c ) y2 [1] # ( d ) (e) Specify the values of expressions (a), (b), (c) and (d) in the following code. import copy x =[1 ,2 ,3] y1 =[ x ,0] y2 = copy . deepcopy ( y1 ) y2 [0][0]=0 y2 [1]=1 y1 [0][0] # ( a ) y1 [1] # ( b ) y2 [0][0] # ( c ) y2 [1] # ( d ) (f) What is the value of l after steps (a), (b), (c) and (d) below? l =[1 ,2 ,3] l [2:3]=4 # ( a ) l [1:3]=[0] # ( b ) l [1:1]=1 # ( c ) l [2:]=[] # ( d ) 2 2. Lists and types: We define the following nested list: q = [[’a’,’b’,’c’],[’d’,’e’,’f’],[’g’,’h’]]. We can visit all elements of q using this nested for loop: for i in q : for j in range ( len ( i ) ) : print i [ j ] What type of objects are i and j? 3. Lists: Creation using loops: Rewrite the generation of the nested list q, q = [ r **2 for r in [10** i for i in range (5) ]] by using standard for loop instead of list comprehension. 4. Lists and loops: One may use an approximate formula for quickly converting Fahrenheit (F) to Celsius (C) degrees: C ≈ C̃ = (F − 30)/2. Write a program to build a table conversion such that conversion[i] holds a row: [F[i], C[i], CApprox[i]] where F[i] is a F degree; C[i] is the corresponding C degree and CApprox[i] is the approximate C degree. The first column of the table is 0, 10, 20, · · ·, 100. 5. Lists and loops: Write a function which takes a two-level nested list inp of integers as an input and outputs a list outp such that outp[i] is the maximum of all numbers in inp[t], where 1 ≤ t ≤ len(inp) and 1 ≤ i ≤ len(inp). You can assume that inp[i] is never empty. Test Cases: Test case 1: Input: Output: inp=[[1,2,3], [4,5]] outp=[3,5] Test case 2: Input: Output: inp=[[1,2,3], [1,7], [32,3,4]] outp=[3,7,32] Test case 3: Input: Output: inp=[[3,4,5,2],[1,7],[8,0,-1],[2]] outp=[5, 7, 8, 2] Test case 4: Input: Output: inp = [[100],[1,7],[8,0,-1],[2]] outp=[100, 7, 8, 2] Test case 5 Input: Output: inp = [[3,4,5,2]] outp: [5] 6. Lists: Given the following: 3 >>> a = [1 ,2 ,3] >>> a [1] = a What will be the displayed for print a at this point? Explain why. 7. Lists and loops: Write a function that takes a value N and returns an N by N multiplication table in the form of a nested list. For instance, if N is seven, your program will return the following table as a nested list. 1 2 3 4 5 6 7 2 4 6 8 10 12 14 3 6 9 12 15 18 21 4 8 12 16 20 24 28 5 10 15 20 25 30 35 6 12 18 24 30 36 42 7 14 21 28 35 42 49 The first element of the nested list should be a list that represents the first row of the table, the second element represents the second row and so on. For n < 2 your function should return the value None. Test Cases: Test case 1 Input: Output: N=7 [[1, 2, 3, 4, 5, 6, 7], [2, 4, 6, 8, 10, 12, 14], [3, 6, 9, 12, 15, 18, 21], [4, 8, 12, 16, 20, 24, 28], [5, 10, 15, 20, 25, 30, 35], [6, 12, 18, 24, 30, 36, 42], [7, 14, 21, 28, 35, 42, 49]] Test case 2 Input: Output: N=1 None Test case 3 Input: Output: N=0 None Test case 4 Input: Output: N=2 [[1, 2], [2, 4]] Test case 5 Input: Output: N=-1 None 8. Loops and random numbers: Write a program for estimating the probability of getting at least one 6 when throwing n dice. Assume that the dice being rolled has six faces labeled 1 through 6 and the probabilities of getting either face up after rolling the dice are the same. Read n and the number of experiments as inputs. [Hint: In Python you may generate 4 a random integer x, a ≤ x ≤ b, as random.randint(a,b). For example, the statement x=random.randint(1,6) will generate a random integer between 1 and 6 and assign to x. Test Cases: Note: You may get slightly different answers to this problem depending on how many times you throw the dice. numExp below is the number of times the dice is thrown to calculate the probability. Also, even if you throw the dice 100 times in each run of your program, you are likely to obtain different answers. To check your program note that the correct answer is 1 − 5n 6 for n > 0 dice. Your program should estimate a probability close to this number. Answers below are rounded to 2-decimal digits. Test Cases: Test case 1 Input: Output: n = 1, numExp = 100000 0.17 Test case 2 Input: Output: n = 1, numExp = 200000 0.17 Test case 3 Input: Output: n = 1, numExp = 300000 0.17 Test case 4 Input: Output: n = 2, numExp = 500000 0.31 Test case 5 Input: Output: n = 2, numExp = 600000 0.31 9. Loops and random numbers: Somebody suggests the following game. You invest $1 and are allowed to throw four dice. If the sum of the eyes on the dice is less than 9, you win r dollars, otherwise you lose your investment. Should you play this game when r = 10? Answer the question by citing a program that simulates the game. Read r and the number of experiments N as inputs. 10. Recursion: GCD revisited: Euclid’s algorithm to calculate the greatest common divisor of two positive integers a and b, often written as gcd(a, b), is recursively defined as: if a = b; a gcd(a − b, b) if a > b; gcd(a, b) = gcd(a, b − a) if b > a. Implement the algorithm as a Python function. 5 Test Cases: Test case 1 Input: Output: a=5, b=37 1 Test case 2 Input: Output: a=2, b=2 2 Test case 3 Input: Output: a=50, b=10 10 Test case 4 Input: Output: a=1, b=15 1 Test case 5 Input: Output: a=3000, b=2000 1000 6 Problems: Homework 1. Functions and loops: Newton’s method for finding a root of a polynomial: Given a polynomial p(x), one may use the Newton’s method to find a root of p(x) using the following algorithm. (a) Let r0 be an initial approximation of the root. Almost any approximation works in many cases (but not necessarily!). (b) Compute rn+1 = rn − p(rn ) , where n ≥ 0 and p0 (rn ) is the first derivative of p(x) p0 (rn ) evaluated at rn . (c) Continue applying the above step to obtain new estimates rn+1 of the root. The process may be terminated when | rn − rn−1 |< , where is some small quantity. Write a function named rootFinder() that takes a polynomial p(), its derivative p0 (), initial approximation of its root, and as inputs and returns an estimate of a root of p(x). Test your function with the following polynomials. p1 (x) = (x − 2)(x − 3)(x − 4) = x3 − 9x2 + 26x − 24 p2 (x) = (x − 2)(x − 2)(x − 2)(x − 2) = x4 − 8x3 + 24x2 − 32x + 16 p3 (x) = (x − 2)2 − 1 Reference: http://mathworld.wolfram.com/NewtonsMethod.html You may also like to watch the following video to understand when the Newton’s method might fail: http: //www.youtube.com/watch?v=9RjI_so9oSM. Test Cases: In the test cases below, func1 denotes the polynomial one of whose roots is to be found and func2 the first derivative of func1. Test case 1 Input: Output: func1=p1, func2=p1d, r0=1, eps=0.0001 2 Test case 2 Input: Output: func1=p2, func2=p2d, r0=1, eps=0.0001 2 Test case 3 Input: Output: func1=p2, func2=p2d, r0=-1, eps=0.0001 2 7 Test case 4 Input: Output: func1=p3, func2=p3d, r0=0, eps=0.0001 1 Test case 5 Input: Output: func1=p3, func2=p3d, r0=-1, eps=0.0001 1 2. Loops: Two words of equivalent length “interlock” if selecting alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled.” Write a function which takes (word1, word2, word3) as input and return true if and only if word1 and word2 interlock and generates word3. Test Cases: Test case 1 Input: Output: word1=“shoe”, word2=“cold”, word3=“schooled” True Test case 2 Input: Output: word1=“shoes”, word2=“cold”, word3=“schooled” False Test case 3 Input: Output: word1=“”, word2=“cold”, word3=“schooled” False Test case 4 Input: Output: word1=“shoes”, word2=“cold”, word3=“” False Test case 5 Input: Output: word1=“”, word2=“”, word3=“” False Test case 6 Input: Output: word1=“can”, word2=“his”, word3=“chains” True 3. Functions and loops: Simpson’s rule for numerical integration: Another method for numerical integration uses the Simpson’s rule. Sometimes this method produces more accurate answers than the trapezoidal rule. Given a single valued and continuous function f (x), the following formula corresponds to the Simpson’s rule and works well for small values of h even when the function is not smooth over the interval of integration. Z a b n/2−1 n/2 X X h f (x)dx ≈ f (x0 ) + 2 f (x2j ) + 4 f (x2j−1 ) + f (xn ) 3 j=1 j=1 8 Here h = (b − a)/n, x0 = a, xn = b, and xj = a + jh, for j = 0, 1, 2 . . . n − 1, n. Write a function named simpsonsRule(), that takes a function f (), integer n > 1, limits Rb a and b as inputs and returns an approximation to a f (x)dx. Use your function to approximate each of the following integrals. To understand the accuracy of the numerical method used in this problem, manually compute the error in the approximation obtained numerically. For each integral, compare the errors obtained when using the Simpson’s rule with those obtained using the n-point trapezoidal rule. Z 3 x2 dx 1 Z π sin(x)dx 0 Z 1 e−x dx −1 Note: For those of you who want to learn more about numerical integration read the following article on Simpson’s rule http://en.wikipedia.org/wiki/Simpson%27s_rule. Test Cases: Note: All outputs below are rounded to two decimal digits. Test case 1 Input: Output: f=x2 , n=1000, a=1, b=3 8.67 Test case 2 Input: Output: f=sin(x), n=1000, a=0, b=π 2.0 Test case 3 Input: Output: f=e−x , n=1000, a=-1, b=1 2.35 9 Problems: Exercises 1. Write a program to approximate the value of π using Monte Carlo simulation. 2. Let p1 (x) and p2 (x) be two polynomials of order n > 0 and m > 0, respectively. Thus, we have p1 (x) = a0 xn + a1 xn−1 + . . . an and p2 (x) = a0 xm + a1 xm−1 + . . . am . Let the lists c1 = [a0 a1 . . . an−1 an ] and c2 = [b0 b1 . . . bm−1 bm ] be, respectively, the coefficients of the two polynomials. Write a function named polyMult that takes the two lists of coefficients as input and returns a new list of coefficients that correspond to the coefficients of the polynomial p3 (x) = p1 (x) ∗ p2 (x). For example, if p1 (x) = x3 −x2 −3x+2 and p2 (x) = x+3 then p3 (x) = x4 +2x3 −6x2 −7x+6. In this case we have c1 = [1 − 1 − 3 2] and c2 = [1 3]. The resulting list of coefficients should be c3 = [1 2 − 6 − 7 6]. Test Cases: Test case 1 Input: Output: c1=[1, -1, -3, 2], c2=[1, 3] [1, 2, -6, -7, 6] Test case 2 Input: Output: c1=[1, 3], c2=[1, -1, -3, 2] [1, 2, -6, -7, 6] Test case 3 Input: Output: c1=[0], c2=[1, 3] [0, 0, 0] Test case 4 Input: Output: c1=[1, -1, -3, 2], c2=[] [0, 0, 0, 0, 0] Test case 5 Input: Output: c1=[1, -2], c2=[1, 2] [1, 0, -4] 3. Recursion: prime factors: A prime number is a prime integer p, greater than 1, which is not evenly divisible by any positive integers other than p and 1. Examples are 17, 23, and 211. Any positive integer greater than 1 may be written as a product of primes. For example: 516 = 2 ∗ 2 ∗ 3 ∗ 43. Write a recursive program which, given n, returns a list of prime numbers whose product is n. Test Cases: Test case 1 Input: n=15 10 Output: [5, 3] Test case 2 Input: Output: n=21 [7, 3] Test case 3 Input: Output: n=50 [5, 5, 2] Test case 4 Input: Output: n=13 [13] Test case 5 Input: Output: n=1 [1] End of Problem Set 3. 11
© Copyright 2026 Paperzz