# 12.5E: Exercises - Mathematics

### Practice Makes Perfect

Exercise (PageIndex{19}) Use Pascal's Triangle to Expand a Binomial

In the following exercises, expand each binomial using Pascal’s Triangle.

1. ((x+y)^{4})
2. ((a+b)^{8})
3. ((m+n)^{10})
4. ((p+q)^{9})
5. ((x-y)^{5})
6. ((a-b)^{6})
7. ((x+4)^{4})
8. ((x+5)^{3})
9. ((y+2)^{5})
10. ((y+1)^{7})
11. ((z-3)^{5})
12. ((z-2)^{6})
13. ((4x-1)^{3})
14. ((3x-1)^{5})
15. ((3 x-4)^{4})
16. ((3 x-5)^{3})
17. ((2 x+3 y)^{3})
18. ((3 x+5 y)^{3})

2. (egin{array}{l}{a^{8}+8 a^{7} b+28 a^{6} b^{2}+56 a^{5} b^{3}} {+70 a^{4} b^{4}+56 a^{3} b^{5}+28 a^{2} b^{6}} {+8 a b^{7}+b^{8}}end{array})

4. (egin{array}{l}{p^{9}+9 p^{8} q+36 p^{7} q^{2}+84 p^{6} q^{3}} {+126 p^{5} q^{4}+126 p^{4} q^{5}+84 p^{3} q^{6}} {+36 p^{2} q^{7}+9 p q^{8}+q^{9}}end{array})

6. (egin{array}{l}{a^{6}-6 a^{5} b+15 a^{4} b^{2}-20 a^{3} b^{3}} {+15 a^{2} b^{4}-6 a b^{5}+b^{6}}end{array})

8. (x^{3}+15 x^{2}+75 x+125)

10. (egin{array}{l}{y^{7}+7 y^{6}+21 y^{5}+35 y^{4}+35 y^{3}} {+21 y^{2}+7 y+1}end{array})

12. (egin{array}{l}{z^{6}-12 z^{5}+60 z^{4}-160 z^{3}+240 z^{2}} {-192 z+64}end{array})

14. (egin{array}{l}{243 x^{5}-405 x^{4}+270 x^{3}-90 x^{2}} {+15 x-1}end{array})

16. (27 x^{3}-135 x^{2}+225 x-125)

18. (27 x^{3}+135 x^{2} y+225 x y^{2}+125 y^{3})

Exercise (PageIndex{20}) Evaluate a Binomial Coefficient

1. (left( egin{array}{l}{8} {1}end{array} ight))
2. (left( egin{array}{l}{10} {10}end{array} ight))
3. (left( egin{array}{l}{6} {0}end{array} ight))
4. (left( egin{array}{l}{9} {3}end{array} ight))
1. (left( egin{array}{l}{7} {1}end{array} ight))
2. (left( egin{array}{l}{4} {4}end{array} ight))
3. (left( egin{array}{l}{3} {0}end{array} ight))
4. (left( egin{array}{l}{5} {3}end{array} ight))
1. (left( egin{array}{l}{3} {1}end{array} ight))
2. (left( egin{array}{l}{9} {9}end{array} ight))
3. (left( egin{array}{l}{7} {0}end{array} ight))
4. (left( egin{array}{l}{5} {3}end{array} ight))
1. (left( egin{array}{l}{4} {1}end{array} ight))
2. (left( egin{array}{l}{5} {5}end{array} ight))
3. (left( egin{array}{l}{8} {0}end{array} ight))
4. (left( egin{array}{l}{11} {9}end{array} ight))

2.

1. (7)
2. (1)
3. (1)
4. (45)

4.

1. (4)
2. (1)
3. (1)
4. (55)

Exercise (PageIndex{21}) Use the Binomial Theorem to Expand a Binomial

In the following exercises, expand each binomial.

1. ((x+y)^{3})
2. ((m+n)^{5})
3. ((a+b)^{6})
4. ((s+t)^{7})
5. ((x-2)^{4})
6. ((y-3)^{4})
7. ((p-1)^{5})
8. ((q-4)^{3})
9. ((3x-y)^{5})
10. ((5x-2y)^{4})
11. ((2x+5y)^{4})
12. ((3x+4y)^{5})

2. (egin{array}{l}{m^{5}+5 m^{4} n+10 m^{3} n^{2}+10 m^{2} n^{3}} {+5 m n^{4}+n^{5}}end{array})

4. (egin{array}{l}{s^{7}+7 s^{6} t+21 s^{5} t^{2}+35 s^{4} t^{3}} {+35 s^{3} t^{4}+21 s^{2} t^{5}+7 s t^{6}+t^{7}}end{array})

6. (y^{4}-12 y^{3}+54 y^{2}-108 y+81)

8. (q^{3}-12 q^{2}+48 q-64)

10. (egin{array}{l}{625 x^{4}-1000 x^{3} y+600 x^{2} y^{2}} {-160 x y^{3}+16 y^{4}}end{array})

12. (egin{array}{l}{243 x^{5}+1620 x^{4} y+4320 x^{3} y^{2}} {+5760 x^{2} y^{3}+3840 x y^{4}+1024 y^{5}}end{array})

Exercise (PageIndex{22}) Use the Binomial Theorem to Expand a Binomial

In the following exercises, find the indicated term in the expansion of the binomial.

1. Sixth term of ((x+y)^{10})
2. Fifth term of ((a+b)^{9})
3. Fourth term of ((x-y)^{8})
4. Seventh term of ((x-y)^{11})

2. (126a^{5} b^{4})

4. (462x^{5} y^{6})

Exercise (PageIndex{23}) Use the Binomial Theorem to Expand a Binomial

In the following exercises, find the coefficient of the indicated term in the expansion of the binomial.

1. (y^{3}) term of ((y+5)^{4})
2. (x^{6}) term of ((x+2)^{8})
3. (x^{5}) term of ((x-4)^{6})
4. (x^{7}) term of ((x-3)^{9})
5. (a^{4} b^{2}) term of ((2 a+b)^{6})
6. (p^{5} q^{4}) term of ((3 p+q)^{9})

2. (112)

4. (324)

6. (30,618)

Exercise (PageIndex{24}) Writing Exercises

1. In your own words explain how to find the rows of the Pascal's Triangle. Write the first five rows of Pascal's Triangle.
2. In your own words, explain the pattern of exponents for each variable in the expansion of.
3. In your own words, explain the difference between ((a+b)^{n}) and ((a-b)^{n}).
4. In your own words, explain how to find a specific term in the expansion of a binomial without expanding the whole thing. Use an example to help explain.

## Self Check

a. After completing the exercises, use this checklist to evaluate your mastery of the objectives of this section.

b. On a scale of 1-10, how would you rate your mastery of this section in light of your responses on the checklist? How can you improve this?

## Course Requirements

You will be expected to complete online homework in this course. Your online homework will allow you to brush up on prerequisite math skills, as well as check for your conceptual understanding of the course material. It is recommended you work the HW before the quizzes, which cover the material at the more rigorous MATH 1332 level.

TAKE-HOME QUIZZES

You will be expected to complete take-home homework quizzes for this course. If you are absent and would like your Take-home Quiz to count as on time, drop it off in Marisa Bjorland&rsquos mailbox (Building A mail room) or office RVSG 9121, or email it to [email protected] Late Take-Home Quizzes will be graded for feedback only, and will receive a grade of zero. We will drop the lowest Take-Home Quiz grade from your average

QUICK QUIZZES

Every Monday and Wednesday, we will have a quick 1-2 question quiz at the beginning of class. The quiz will cover material from the previous 2 classes and the corresponding homework. Quizzes will be open note and you may use your homework to help, as well as work with other classmates.

Come to class on time so that you don&rsquot miss the quiz.

GROUP WORK AND PARTICIPATION

You are going to interact with each other quite a bit and talk to each other about math. You are expected to be an active participant and contribute to the discussion of the problems on the group activities. Though you will be working with other students, everyone will record the work on their own paper. These will be your notes you will use to complete homework assignments, so you need to ask questions and make sure you understand the ideas in the activity.

I know that some of you do not like to talk in class and others of you like to talk a lot. So, we will follow a couple of easy rules. We give everyone a chance to talk. We respond to whatever anyone says with respect. We are concerned here about concepts that will help you succeed in your college-level math courses and ultimately achieve your academic goals. You are all in the same boat I expect that students in this class will support each other and be respectful when working together.

· Your class activities will be checked every day during class.

There will be five exams given in a proctored setting during class time or in the Testing Center. There will also be an optional sixth exam. If you choose to take it, the optional sixth exam grade will replace the lowest exam grade. No make-up exams will be given. If you miss an exam, you will be required to take the sixth exam. If you miss a second exam for any reason, that grade will be a zero.

The same exams, quizzes, and homework are used to determine both the MATD 0385 and MATH 1332 grades. Only the weighting of the grade calculation is different.

· MATD 0385
Exams 50%
Take-Home Quizzes 20%
Homework 20%
Group Work/Participation + 10%
100%

A = 90% - 100% ● B = 80% - 89% ● C = 70% - 79% ● D = 60% - 69% ● F = 59% and below

· MATH 1332
Exams 75%
Take-Home Quizzes 10%
Quick Quizzes 5%

Homework + 10%

A = 90% - 100% ● B = 80% - 89% ● C = 70% - 79% ● D = 60% - 69% ● F = 59% and below

## Exercises INF3331 H12

Remember that all assignments, when possible, should be well documented and supplied with a runtime example. If the program is not working, a pseudo runtime example must be provided. Failing to meet these requirements automatically disqualifies the assignment from being approved.

### Week 1: Sept 3-7 (Bash intro)

#### 1.1 Modify the scientific 'Hello world' script

Write a script that takes as input a string containing a mathematical expression, evaluates the expression and prints the result to the screen. Example of use:

Name of scriptfile: hw.sh (exercise class: Bash)

#### 1.2 Use find to bundle files

Write a script that takes as input a directory (path) name and a filename base (such as "*.*", "*.txt" etc). The script shall search the given directory tree, find all files matching the given filename, and bundle them into a single file. Executing the given file as a script should return the original files. Hint: Combine the find command with the bundle script from the lectures.

Name of scriptfile: bundle.sh (exercise class: Bash)

#### 1.3 Eternal loop interrupted with Ctr-C

Write a script that takes no input arguments, and repeatedly writes "All work an no play makes Jack a dull boy." The loop should be eternal, but when interrupted by Ctrl-C the script should print a suitable message to the screen before exiting. Hint: Use the bash line " trap control_c SIGINT" to capture the Ctrl-C interruption.

Name of scriptfile: jack.sh (exercise class: Bash)

### Week 2: Sep 10-Sep 14 (Python intro)

#### 2.1 Become familiar with electronic Python documentation

Write a script that prints a uniformly distributed random number between -1 and 1 on the screen. The number should be written with four decimals as implied by the %.4fformat.

To create the script file, you can use a standard editor such as Emacs or Vim on Unix-like systems. On Windows you must use an editor for pure text files - Notepad is a possibility, but I prefer to use Emacs or the IDLE'' editor that comes with Python (you usually find IDLE on the start menu, choose File--New Window to open up the editor). IDLE supports standard key bindings from Unix, Windows, or Mac (choose Options--Configure IDLE. and Keys to get a menu where you can choose between the three classes of key bindings).

The standard Python module for generation of uniform random numbers is calledrandom. To figure out how to use this module, you can look up the description of the module in the Python Library Reference. Load the file $scripting/doc.html into a Web browser and click on the link Python Library Reference: Index. You will then see the index of Python functions, modules, data structures, etc. Find the item random (standard module) in the index and follow the link. This will bring you to the manual page for the random module. In the bottom part of this page you will find information about functions for drawing random numbers from various distributions (do not use the classes in the module, use plain functions). Also apply pydoc to look up documentation of the random module: just write pydoc random on the command line. Name of scriptfile: printrandom.py (exercise class: Python) #### 2.2 Extend Exercise 2.1 with a loop Extend the script from Exercise 2.1 such that you draw n random uniformly distributed numbers, where n is given on the command line, and compute the average of these numbers. Name of scriptfile: averagerandom.py (exercise class: Python) #### 2.3 Find five errors in a script Consider the following Python code: There are five errors in this file - find them! Name of scriptfile: averagerandom2.py (exercise class: Python) #### 2.4 Basic use of control structures To get some hands-on experience with writing basic control structures in Python, we consider an extension of the Scientific Hello World script hw.py from Chapter 2.1 in the book (see also the lecture notes). The script is now supposed to read an arbitrary number of command-line arguments and write the sine of each number to the screen. Let the name of the new script be hw2a.py. As an example, we can write and the program writes out Traverse the command-line arguments using a for loop. The complete list of the command-line arguments can be written sys.argv[1:] (i.e., the entries in sys.argv, starting with index 1 and ending with the last valid index). The for loop can then be written as for r in sys.argv[1:]. Make an alternative script, hw2b.py, where a while loop construction is used for handling each number on the command line. In a third version of the script, hw2c.py, you should take the natural logarithm of the numbers on the command line. Look up the documentation of the math module in the Python Library Reference to see how to compute the natural logarithm of a number. Include an if test to ensure that you only take the logarithm of positive numbers. Running, for instance, Name of scriptfiles: hw2a.py, hw2b.py, hw2c.py (exercise class: Python) ### Week 3: Sep 17-21 (Python tasks) #### 3.1 Combine two-column data files to a multi-column file Write a script inverseconvert.py that performs the 'inverse process' of the following script: For example, if we first apply the script above to the specific test file: we get three two-column files tmp-measurements.dat, tmp-model1.dat, and tmp-model2.dat. Running should in this case create a file outfile, which is almost identical to the test file above. Only the first line should differ (inverseconvert.py can write anything on the first line). For simplicity, we give the time step parameter explicitly as a command-line argument (it could also be found from the data in the files). Hint: When parsing the command-line arguments, one needs to extract the name model1 from a filename model1.dat stored in a string (say) s. This can be done by s[:-4] (all characters in s except the last four ones). Chapter 3.4.5 describes some tools that allow for a more general solution to extracting the name of the time series from a filename. Name of scriptfile: inverseconvert.py (exercise class: Python) #### 3.2 Annotate a filename with the current date Write a function that adds the current date to a filename. For example, calling the function with the text myfile as argument results in the string myfile_Aug22_2010being returned if the current date is August 22, 2010. Read about the time module in the Python Library Reference to see how information about the date can be obtained. Name of scriptfile: add_date.py (exercise class: Python) #### 3.3 Make a specialized sort function Suppose we have a script that performs numerous efficiency tests. The output from the script contains lots of information, but our purpose now is to extract information about the CPU time of each test and sort these CPU times. The output from the tests takes the following form: First we need to extract the lines starting with CPU-time. Then we need to sort the extracted lines with respect to the CPU time, which is the number appearing in the second column. Write a script to accomplish this task. A suitable testfile with output from an efficiency test can be found here. Hint: Find all lines with CPU time results by using a string comparison of the first 7 characters to detect the keyword CPU-time. Then write a tailored sort function for sorting two lines (extract the CPU time from the second column in both lines and compare the CPU times as floating-point numbers). Name of scriptfile: ranking.py (exercise class: Python) ### Week 4: Sep 24-28 (Regular Expressions) #### 4.1 Count words in a text Write a script that reads a filename and a word from the command line, and reports the number of times the word occures in the file. When an optional argument -i is provided at the command line, the count should be case insensitive. Another command line flag -b should make the script respect word boundaries. Consider the following text in the file football.txt: Running the script count_words.py on this file should report: Name of scriptfile: count_words.py (exercise class: Regex) #### 4.2 Find errors in regular expressions Consider the following script: Running this script produces the output while the desired output is Go through the script, make sure you understand all details, figure out how the various parts are matched by the regular expression, and find the error. Name of scriptfile: regexerror.py (exercise class: Regex) #### 4.3 Explain the behavior of regular expressions We want in a user interface to offer a compact syntax for loops: [0:12,4] means a loop from 0 up to and including 12 with steps of 4 (i.e., 0, 4, 8, 12). The comma and step is optional, so leaving them out as in [3.1:5] implies a unit step (3.1 and 4.1 are generated in this example). Consider the two suggestions for suitable regular expressions below. Both of them fail: Explain in detail why the regular expressions fail. Use this insight to construct a regular expression that works. Name of scriptfile: loop_regex.py (exercise class: Regex) #### 4.4 Interpret a regex code and find programming errors The following code segment is related to extracting lower and upper limits of intervals (read Chapters 8.2.5 and 8.2.6): Execute the Python code and observe that it reports an error (index out of bounds in the upper = assignment). Try to understand what is going on in each statement, print out groups, and correct the code. Name of scriptfile: findallerror.py (exercise class: Regex) ### Week 5: Oct 1-5 (Regular expressions, Python tasks) #### 5.1 Generate data from a user-supplied formula Suppose you want to generate files with (x,y) data in two columns, where y is given by some function f(x). (Such files can be manipulated by, e.g., the datatrans1.py script from Chapter 2.2.) You want the following interface to the generation script: x values are generated, starting with start and ending with stop, in increments of step. For each x value, you need to compute the textual expression in func, which is an arbitrary, valid Python expression for a function involving a single variable with name x, e.g., 'x**2.5*cosh(x)' or 'exp(-(x-2)**2)'. You can assume that from math import * is executed in the script. Here is an example of generating 1001 data pairs (x,y), where x=0,0.5,1,1.5. 500 and f(x)=x*sin(x): The xygenerator.py script should write to standard output - you can then easily direct the output to a file. Try to write the xygenerator.py script as compactly as possible. You will probably be amazed about how much that can be accomplished in a 10+ line Python script! (Hint: use eval.) Name of scriptfile: xygenerator.py (exercise class: Regex) #### 5.2 Write an improved function for joining strings Perl's join function can join an arbitrary composition of strings and lists of strings. The purpose of this exercise is to write a similar function in Python (the string.join function, or the built-in join function in string objects, can only join strings in a list object). The function must handle an arbitrary number of arguments, where each argument can be a string, a list of strings, or a tuple of strings. The first argument should represent the delimiter. As an illustration, the function, here called join, should be able to handle the following example: The resulting strings ex1 and ex2 should read Hint: Variable number of arguments in functions is treated in Chapter 3.3.3, whereas Chapter 3.2.11 explains how to check the type of the arguments. Name of scriptfile: join.py (exercise class: Python) #### 5.3 Use tools to document a script Equip one of your previous scripts with doc strings. Use either HappyDoc or Epydoc and their light-weight markup languages to produce HTML documentation of the script. The documentation should be user-oriented in a traditional man page style, and both the documentation and the documented script should be handed in. Name of scriptfile: your_script.py, your_doc.html (exercise class: Python) #### 5.4 Prefix name of digital image files with date and time JPEG images taken by digital cameras normally have names like img_1238.jpg. For sorting purposes it might be convenient to have the time and date when the picture was taken as an initial part of the filename. Modern digital cameras encode a lot of information about the picture, including the time and date, into a header in the JPEG file. The coding scheme of the header often vary with the camera vendor, apparently making it necessary to use vendor-specific software to extract picture information. However, the jhead program can parse JPEG headers coming from most digital cameras. Running jhead on a JPEG file results in output like Write a Python function gettime that reads a text like the one above, extracts, the time and date when the picture was taken (Date/Time), and returns the time and date information as two tuples of strings (HH,MM,SS) and (YYYY,MM,DD). The first tuple corresponds to the time HH:MM:SS (hours, minutes, seconds), whereas the second tuple corresponds to the date YYYY:MM:DD (year, month, day). (Hint: It might be convenient to split each line wrt. : into a list l, re-join l[1:], split wrt. whitespace, and then wrt. :.) Write another Python function prefix that takes the time and date string tuples from gettime as input, together with the name of the image file, and prefixes the filename with the date and time. For example, if img_4978.jpg is the original filename, and the tuples returned from gettime are (18,10,03) and (2002,05,19), the returned string from prefix reads If the filename already is on this form, no prefix should be added (i.e., the original filename is returned). In case you have collections of images produced by digital cameras, the filenaming functionality presented in this exercises can be very convenient. The JPEG header is destroyed by many photo manipulation and viewing programs, so keeping the date in the filename preserves this important information. Since the JPEG header is easily destroyed, you should apply jhead and the renaming procedure to fresh files not yet being processed by programs. Name of scriptfile: jpegrename.py (exercise class: Python) ### Week 6: Oct 8-12 (Python tasks) #### 6.1 Find the paths to a collection of programs A script often makes use of other programs, and if these programs are not available on the computer system, the script will not work. This exercise shows how you can write a general function that tests whether the required tools are available or not. You can then terminate the script and notify to the user about the software packages that need to be installed. The idea is to write a function findprograms that takes a list of program names as input and returns a dictionary with the program names as keys and the programs' complete paths on the current computer system as values. Search the directories in the PATH environment variable for the desired programs (see Chapter 3.2.5). Allow a list of additional directories to search in as an optional argument to the function. Programs that are not found should have the value None in the returned dictionary. Here is an illustrative example of using findprograms to test for the existence of some utility programs used in the course: Name of scriptfile: findprograms.py (exercise class: Python) #### 6.2 Find old and large files in a directory tree Write a function that traverses a user-given directory tree and returns a list of all files that are larger than X Mb and that have not been accessed the last Y days, where X and Y are parameters to the function. Include an option in this function that moves the files to a subdirectory trash under /tmp (you need to create trash if it does not exist). Hints: Use shutil.copy and os.remove to move the files (and not os.rename it will not work for moving files across different filesystems). First build a list of all files to be removed. Thereafter, remove the files physically. The age of a file can be tested with os.path.getatime or the os.stat functions. Read about these functions in the Python Library Reference. You may also want to read about the time module. To test the script, you can run a script fakefiletree.py that generates a directory tree (say) tmptree with files having arbitrary age (up to one year) and arbitrary size between 5 Kb and 10 Mb: If you find that fakefiletree.py generates too many large files, causing the disk to be filled up, modify the arguments in the maketree function call. Remember to remove tmptreewhen you have finished the testing. Name of scriptfile: old_and_large.py (exercise class: Python) #### 6.3 Estimate the chance of an event in a dice game What is the probability of getting at least one 6 when throwing two dice? This question can be analyzed theoretically by methods from probability theory (the result is 1/6 + 1/6 - (1/6)*(1/6) = 11/36). However, a much simpler and much more general alternative is to let a computer program 'throw' two dice a large number of times and count how many times a 6 shows up. Such type of computer experiments, involving uncertain events, is often called Monte Carlo simulation. Create a script that in a loop from 1 to n draws two uniform random numbers between 1 and 6 and counts how many times p a 6 shows up. Write out the estimated probabilityp/float(n) together with the exact result 11/36. Run the script a few times with different n values (preferably read from the command line) and determine from the experiments how largen must be to get the first three decimals (0.306) of the probability correct. Hint: Check out the random module to see how to draw random uniformly distributed integers in a specified interval. Remark. Division of integers (p/n) yields in this case zero, since p is always smaller than n. Integer p divided by integer n implies in Python, and in most other languages, integer division, i.e., p/n is the largest integer that when multiplied by n becomes less than or equal to p. Converting at least one of the integers to float (p/float(n)) ensures floating-point division, which is what we need. Name of scriptfile: dice2.py (exercise class: Python) #### 6.4 Determine if you win or loose a hazard game Somebody suggests the following game. You pay 1 unit of money and are allowed to throw four dice. If the sum of the eyes on the dice is less than 9, you win 10 units of money, otherwise you loose your investment. Should you play this game? Hint: Use the simulation method from Exercise 6.3. Name of scriptfile: dice4.py (exercise class: Python) #### Week 7: Oct 15-19 (Python tasks) #### 7.1 Implement a class for vectors in 3D The purpose of this exercise is to program with classes and special methods. Create a class Vec3D with support for the inner product, cross product, norm, addition, subtraction, etc. The following application script demonstrates the required functionality: We remark that class Vec3D is just aimed at being an illustrating exercise. Serious computations with a class for 3D vectors should utilize either a NumPy array (see Chapter 4), or better, the Vector class in the Scientific.Geometry.Vector module, which is a part of ScientificPython (see Chapter 4.4.1). Name of scriptfile: vec3d.py (exercise class: Python) #### 7.2 Extend the class from Exercise 7.1 Extend and modify the Vec3D class from Exericse 8.27 such that operators like + also work with scalars: In the same way we should be able to do a-v, v-a, a*v, v*a, and v/a (a/v is not defined). Name of scriptfile: vec3d_ext.py (exercise class: Python) #### 7.3 Vectorize a constant function does not work properly when x is a NumPy array. In that case the function should return a NumPy array with the same shape as x and with all entries equal to 3.0. Perform the necessary modifications such that the function works for both scalar types and NumPy arrays. Name of scriptfile: vectorize_function.py (exercise class: Python) #### 7.4 Vectorize a numerical integration rule The integral of a function f(x) from x=a to x=b can be calculated numerically by the Trapezoidal rule: where h equals (b-a)/n (the number of integration points is (n+1)). Implement this approximation in a Python function containing a straightforward loop. The code will run slowly compared to a vectorized version. Make the vectorized version and introduce timings to measure the gain of vectorization. Use the functions as test functions for the integration. (Hint: Implement f such that it operates on a vector x of all the evaluation points a+i*h, i=0. n-1.) Name of scriptfile: vectorize_integration.py (exercise class: Python) ### Week 8: Oct 22-26 (Python tasks) #### 8.1 Make a class for sparse vectors The purpose of this exercise is to implement a sparse vector. That is, in a vector of length n, only a few of the elements are different from zero: Implement a class SparseVec with the illustrated functionality. Hint: Store the nonzero vector elements in a dictionary. Name of scriptfile: SparseVec.py (exercise class: Class) #### 8.2 Assignment and in-place modifications of NumPy arrays Consider the following script: Explain why x, y, and z have the same values. How can be script be changed such that y and z get the intended values? Name of scriptfile: NumPy_assignment.py (exercise class: Python) #### 8.3 Implement Exercise 6.3 using NumPy arrays Solve the same problem as in Exercise 6.3, but use NumPy and a vectorized algorithm. That is, generate two (long) random vectors of uniform integer numbers ranging from 1 to 6, find the entries that are 6 in one of the two arrays, count these entries and estimate the probability. Insert CPU-time measurements in the scripts and compare the plain Python loop and the random module with the vectorized version utilizing NumPy functionality. Hint: You may use the following NumPy functions: random.randint, ==, +, >, and sum(read about them in the NumPy reference manual). Name of scriptfile: dice2_NumPy.py (exercise class: Python) #### 8.4 Implement Exercise 6.4 using NumPy arrays Solve the same problem as in Exercise 6.4, but use NumPy and a vectorized algorithm. Generate a random vector of 4*n uniform integer numbers ranging from 1 to 6, reshape this vector into an array with four rows and n columns, representing the outcome of n throws with four dice, sum the eyes and estimate the probability. Insert CPU-time measurements in the scripts and compare the plain Python solution in Exercise 5.4 with the version utilizing NumPy functionality. Hint: You may use the NumPy functions random.randint, sum, and < (read about them in the NumPy reference manual, and notice especially that sum can sum the rows or the columns in a two-dimensional array). Name of scriptfile: dice4_NumPy.py (exercise class: Python) #### 8.5 Process comma-separated numbers in a file Suppose a spreadsheet program stores its table in a file row by row, but with comma-separated rows, as in this example: Write a script that loads the text in the first column into a list of strings and the rest of the numbers into a two-dimensional NumPy array. Sum the elements in each row and write the result as The script should of course treat any number of rows and columns in the file. Try to write the script in a compact way. Name of scriptfile: process_spreadsheet.py (exercise class: Python) ### Week 9: Oct 29-Nov 2 (Python tasks) #### 9.1 Matrix-vector multiply with NumPy arrays Define a matrix and a vector, e.g., Use the NumPy reference manual to find a function that computes the standard matrix-vector product A times b (i.e., the vector whose i-th component is sum from j=0 to 2 ofA[i,j]*b[j]). Name of scriptfile: matvec.py (exercise class: Python) #### 9.2 Replace lists by NumPy arrays Modify the convert2.py script from Chapter 2.5 such that floating-point values are stored in NumPy arrays instead of plain Python lists. Name of scriptfile: convert2_wNumPy.py (exercise class: Python) #### 9.3 Rock, Paper, Scissors ##### Description Rock, paper, scissors, also know as roshambo, is a simple child's game that is frequently used to settle disputes. In the game, a rock breaks the scissors, the scissors cut the paper, and the paper covers the rock. Each option is equally likely to prevail over another. If the players choose the same object a draw is declared and the game is repeated until someone prevails. For more information than you ever thought it was possible to collect about rock, paper, scissors, check out the Web page of the World RPS Society. In this computerized version the human player competes against the computer which chooses a rock, paper, or scissors randomly. The game proceeds until the human player quits the game or until a predetermined score is reached (e.g., 11 pts.) at which time the final tally is displayed. Solutions with fewer numbers of ifstatements are considered more elegant. ##### Input The human player enters the number of points required for a win. During the play of the game the human player selects whether to play a rock, paper, or scissors by using the keyboard. The human player may also end the game by pressing the Control-D sequence at any time. (Ending the game early does not allow a winner to be determined if the human player is ahead.) ##### Output The program will display the winner of each roshambo round along with the running score. At the conclusion of the game, the computer will display the overall winner and the final score. ##### Sample session This exercise is copied from openbookproject.net under the GNU Free Documentation License. Name of scriptfile: roshambo.py #### 9.4 Apply SWIG to an array class in C++ The purpose of this exercise is to wrap the class MyArray (see Chapter 10.2.3 of the course book) such that MyArray objects can be used in Python in almost the same way as it is used in C++. Use SWIG to generate wrapper code. The code for MyArray can be found here MyArray.h MyArray.cpp Name of scriptfile: MyArray_wrap.py #### 9.5 Literary Analysis ##### Description Your English teacher has just asked you to write a paper comparing two of the works from the free, online literature library at Project Gutenberg. Since you are a computer scientist, you decide to put your skills to use. You plan to compare your two favorite works of classic literature in terms of the vocabulary used in each. Since this a bit outside the scope of the assignment as described by your English teacher, you ask for permission before you proceed. Intruiged by your proposal, your English teacher agrees and you are ready to go. You plan to write a program that will take a text file as input and return a report listing alphabetically all the words in the file and the number of occurances of each. This exercise is copied from openbookproject.net under the GNU Free Documentation License. Name of scriptfile: gutenberg.py ### Week 10: Nov 5-9 (Python tasks) #### 10.1 Math Quiz ##### Description The following program runs a math quiz consisting of 10 multiplication problems involving operands between 1 and 10: ## 1 Answer 1 The break even formula for GWM/SS requires a bit of algebra. First, our variables: •$DAM$is average damage per hit before GWM/SS. •$HIT$is bonus to hit before GWM/SS. •$AC$is target armor class. This is all we need to get our formula. We will set expected damage without GWM/SS equal to expected damage with it, and then solve for$AC$. In this initial equation, the left is expected damage without GWM/SS, right is with. The steps for solving for$AC$, left as an exercise to the reader, yield a break even AC of: Note, expected crit damage would be added as a constant on each side of our initial equation, so it is ignored. Further, when the target's AC is so high that the only way to hit it is with a natural 20, which is when$AC-HITgeq20$, it becomes best practice again to take GWM/SS on every attack since the penalty is meaningless. ### The numbers. With a mundane longbow, assuming a proficiency bonus of +4,$DAM=1d8+10=14.5$and$HIT=9$. Then our break even AC is 17.75. This means on average, we should use SS for target ACs 17 and below. With a mundane greatsword, assuming proficiency bonus of +4,$DAM=2d6+10=17$and$HIT=9$. Then our break even AC is 16.5. This means on average, we should use GWM for target ACs 16 and below. These are just examples, the formula is simple enough to substitute your own numbers with little issue. A user named Bacon Bits works this result in greater detail in this answer, go give them some love. ## Week 2: Sep 14-18 (Python tasks) ### Week 1: Sep 7-11 (Python intro) #### 1.1 Become familiar with electronic Python documentation Write a script that prints a uniformly distributed random number between -1 and 1 on the screen. The number should be written with four decimals as implied by the %.4f format. To create the script file, you can use a standard editor such as Emacs or Vim on Unix-like systems. On Windows you must use an editor for pure text files - Notepad is a possibility, but I prefer to use Emacs or the IDLE'' editor that comes with Python (you usually find IDLE on the start menu, choose File--New Window to open up the editor). IDLE supports standard key bindings from Unix, Windows, or Mac (choose Options--Configure IDLE. and Keys to get a menu where you can choose between the three classes of key bindings). The standard Python module for generation of uniform random numbers is called random. To figure out how to use this module, you can look up the description of the module in the Python Library Reference. Load the file$scripting/doc.html into a Web browser and click on the link Python Library Reference: Index. You will then see the index of Python functions, modules, data structures, etc. Find the item random (standard module) in the index and follow the link. This will bring you to the manual page for the random module. In the bottom part of this page you will find information about functions for drawing random numbers from various distributions (do not use the classes in the module, use plain functions). Also apply pydoc to look up documentation of the random module: just write pydoc random on the command line.

Name of scriptfile: printrandom.py (exercise class: Python)

#### 1.2 Extend Exercise 1.1 with a loop

Extend the script from Exercise 1.1 such that you draw n random uniformly distributed numbers, where n is given on the command line, and compute the average of these numbers.

Name of scriptfile: averagerandom.py (exercise class: Python)

#### 1.3 Find five errors in a script

Consider the following Python code:

There are five errors in this file - find them!

Name of scriptfile: averagerandom2.py (exercise class: Python)

#### 1.4 Basic use of control structures

To get some hands-on experience with writing basic control structures in Python, we consider an extension of the Scientific Hello World script hw.py from Chapter 2.1 in the book (see also the lecture notes). The script is now supposed to read an arbitrary number of command-line arguments and write the sine of each number to the screen. Let the name of the new script be hw2a.py. As an example, we can write

and the program writes out

Traverse the command-line arguments using a for loop. The complete list of the command-line arguments can be written sys.argv[1:] (i.e., the entries in sys.argv, starting with index 1 and ending with the last valid index). The for loop can then be written as for r in sys.argv[1:].

Make an alternative script, hw2b.py, where a while loop construction is used for handling each number on the command line.

In a third version of the script, hw2c.py, you should take the natural logarithm of the numbers on the command line. Look up the documentation of the math module in the Python Library Reference to see how to compute the natural logarithm of a number. Include an if test to ensure that you only take the logarithm of positive numbers. Running, for instance,

Name of scriptfiles: hw2a.py, hw2b.py, hw2c.py (exercise class: Python)

### Week 2: Sep 14-18 (Python tasks)

#### 2.1 Combine two-column data files to a multi-column file

Write a script inverseconvert.py that performs the 'inverse process' of the following script:

For example, if we first apply the script above to the specific test file:

we get three two-column files tmp-measurements.dat, tmp-model1.dat, and tmp-model2.dat. Running

should in this case create a file outfile, which is almost identical to the test file above. Only the first line should differ (inverseconvert.py can write anything on the first line). For simplicity, we give the time step parameter explicitly as a command-line argument (it could also be found from the data in the files).

Hint: When parsing the command-line arguments, one needs to extract the name model1 from a filename model1.dat stored in a string (say) s. This can be done by s[:-4] (all characters in s except the last four ones). Chapter 3.4.5 describes some tools that allow for a more general solution to extracting the name of the time series from a filename.

Name of scriptfile: inverseconvert.py (exercise class: Python)

#### 2.2 Annotate a filename with the current date

Write a function that adds the current date to a filename. For example, calling the function with the text myfile as argument results in the string myfile_Aug22_2010 being returned if the current date is August 22, 2010. Read about the time module in the Python Library Reference to see how information about the date can be obtained.

Name of scriptfile: add_date.py (exercise class: Python)

#### 2.3 Make a specialized sort function

Suppose we have a script that performs numerous efficiency tests. The output from the script contains lots of information, but our purpose now is to extract information about the CPU time of each test and sort these CPU times. The output from the tests takes the following form:

First we need to extract the lines starting with CPU-time. Then we need to sort the extracted lines with respect to the CPU time, which is the number appearing in the second column. Write a script to accomplish this task. A suitable testfile with output from an efficiency test can be found here.

Hint: Find all lines with CPU time results by using a string comparison of the first 7 characters to detect the keyword CPU-time. Then write a tailored sort function for sorting two lines (extract the CPU time from the second column in both lines and compare the CPU times as floating-point numbers).

Name of scriptfile: ranking.py (exercise class: Python)

### Week 3: Sep 21-25 (Python tasks)

#### 3.1 Find the paths to a collection of programs

A script often makes use of other programs, and if these programs are not available on the computer system, the script will not work. This exercise shows how you can write a general function that tests whether the required tools are available or not. You can then terminate the script and notify to the user about the software packages that need to be installed.

The idea is to write a function findprograms that takes a list of program names as input and returns a dictionary with the program names as keys and the programs' complete paths on the current computer system as values. Search the directories in the PATH environment variable for the desired programs (see Chapter 3.2.5). Allow a list of additional directories to search in as an optional argument to the function. Programs that are not found should have the value None in the returned dictionary.

Here is an illustrative example of using findprograms to test for the existence of some utility programs used in the course:

Name of scriptfile: findprograms.py (exercise class: Python)

#### 3.2 Find old and large files in a directory tree

Write a function that traverses a user-given directory tree and returns a list of all files that are larger than X Mb and that have not been accessed the last Y days, where X and Y are parameters to the function. Include an option in this function that moves the files to a subdirectory trash under /tmp (you need to create trash if it does not exist).

Hints: Use shutil.copy and os.remove to move the files (and not os.rename it will not work for moving files across different filesystems). First build a list of all files to be removed. Thereafter, remove the files physically. The age of a file can be tested with os.path.getatime or the os.stat functions. Read about these functions in the Python Library Reference. You may also want to read about the time module.

To test the script, you can run a script fakefiletree.py that generates a directory tree (say) tmptree with files having arbitrary age (up to one year) and arbitrary size between 5 Kb and 10 Mb:

If you find that fakefiletree.py generates too many large files, causing the disk to be filled up, modify the arguments in the maketree function call. Remember to remove tmptree when you have finished the testing.

Name of scriptfile: old_and_large.py (exercise class: Python)

#### 3.3 Estimate the chance of an event in a dice game

What is the probability of getting at least one 6 when throwing two dice? This question can be analyzed theoretically by methods from probability theory (the result is 1/6 + 1/6 - (1/6)*(1/6) = 11/36). However, a much simpler and much more general alternative is to let a computer program 'throw' two dice a large number of times and count how many times a 6 shows up. Such type of computer experiments, involving uncertain events, is often called Monte Carlo simulation.

Create a script that in a loop from 1 to n draws two uniform random numbers between 1 and 6 and counts how many times p a 6 shows up. Write out the estimated probability p/float(n) together with the exact result 11/36. Run the script a few times with different n values (preferably read from the command line) and determine from the experiments how large n must be to get the first three decimals (0.306) of the probability correct.

Hint: Check out the random module to see how to draw random uniformly distributed integers in a specified interval.

Remark. Division of integers (p/n) yields in this case zero, since p is always smaller than n. Integer p divided by integer n implies in Python, and in most other languages, integer division, i.e., p/n is the largest integer that when multiplied by n becomes less than or equal to p. Converting at least one of the integers to float (p/float(n)) ensures floating-point division, which is what we need.

Name of scriptfile: dice2.py (exercise class: Python)

#### 3.4 Determine if you win or loose a hazard game

Somebody suggests the following game. You pay 1 unit of money and are allowed to throw four dice. If the sum of the eyes on the dice is less than 9, you win 10 units of money, otherwise you loose your investment. Should you play this game?

Hint: Use the simulation method from Exercise 3.3.

Name of scriptfile: dice4.py (exercise class: Python)

### Week 4: Sep 28 - Oct 2 (Regular Expressions)

#### 4.1 Count words in a text

Write a script that reads a filename and a word from the command line, and reports the number of times the word occures in the file. When an optional argument -i is provided at the command line, the count should be case insensitive. Another command line flag -b should make the script respect word boundaries. Consider the following text in the file football.txt:

Running the script count_words.py on this file should report:

Name of scriptfile: count_words.py (exercise class: Regex)

#### 4.2 Find errors in regular expressions

Consider the following script:

Running this script produces the output

while the desired output is

Go through the script, make sure you understand all details, figure out how the various parts are matched by the regular expression, and find the error.

Name of scriptfile: regexerror.py (exercise class: Regex)

#### 4.3 Explain the behavior of regular expressions

We want in a user interface to offer a compact syntax for loops: [0:12,4] means a loop from 0 up to and including 12 with steps of 4 (i.e., 0, 4, 8, 12). The comma and step is optional, so leaving them out as in [3.1:5] implies a unit step (3.1 and 4.1 are generated in this example). Consider the two suggestions for suitable regular expressions below. Both of them fail:

Explain in detail why the regular expressions fail. Use this insight to construct a regular expression that works.

Name of scriptfile: loop_regex.py (exercise class: Regex)

#### 4.4 Interpret a regex code and find programming errors

The following code segment is related to extracting lower and upper limits of intervals (read Chapters 8.2.5 and 8.2.6):

Execute the Python code and observe that it reports an error (index out of bounds in the upper = assignment). Try to understand what is going on in each statement, print out groups, and correct the code.

Name of scriptfile: findallerror.py (exercise class: Regex)

### Week 5: Oct 12-16 (Regular expressions, Python tasks)

#### 5.1 Generate data from a user-supplied formula

Suppose you want to generate files with (x,y) data in two columns, where y is given by some function f(x). (Such files can be manipulated by, e.g., the datatrans1.py script from Chapter 2.2.) You want the following interface to the generation script:

x values are generated, starting with start and ending with stop, in increments of step. For each x value, you need to compute the textual expression in func, which is an arbitrary, valid Python expression for a function involving a single variable with name x, e.g., 'x**2.5*cosh(x)' or 'exp(-(x-2)**2)'. You can assume that from math import * is executed in the script.

Here is an example of generating 1001 data pairs (x,y), where x=0,0.5,1,1.5. 500 and f(x)=x*sin(x):

The xygenerator.py script should write to standard output - you can then easily direct the output to a file.

Try to write the xygenerator.py script as compactly as possible. You will probably be amazed about how much that can be accomplished in a 10+ line Python script! (Hint: use eval.)

Name of scriptfile: xygenerator.py (exercise class: Regex)

#### 5.2 Write an improved function for joining strings

Perl's join function can join an arbitrary composition of strings and lists of strings. The purpose of this exercise is to write a similar function in Python (the string.join function, or the built-in join function in string objects, can only join strings in a list object). The function must handle an arbitrary number of arguments, where each argument can be a string, a list of strings, or a tuple of strings. The first argument should represent the delimiter. As an illustration, the function, here called join, should be able to handle the following example:

The resulting strings ex1 and ex2 should read

Hint: Variable number of arguments in functions is treated in Chapter 3.3.3, whereas Chapter 3.2.11 explains how to check the type of the arguments.

Name of scriptfile: join.py (exercise class: Python)

#### 5.3 Use tools to document a script

Equip one of your previous scripts with doc strings. Use either HappyDoc or Epydoc and their light-weight markup languages to produce HTML documentation of the script. The documentation should be user-oriented in a traditional man page style, and both the documentation and the documented script should be handed in.

Name of scriptfile: your_script.py, your_doc.html (exercise class: Python)

#### 5.4 Prefix name of digital image files with date and time

JPEG images taken by digital cameras normally have names like img_1238.jpg. For sorting purposes it might be convenient to have the time and date when the picture was taken as an initial part of the filename. Modern digital cameras encode a lot of information about the picture, including the time and date, into a header in the JPEG file. The coding scheme of the header often vary with the camera vendor, apparently making it necessary to use vendor-specific software to extract picture information. However, the jhead program can parse JPEG headers coming from most digital cameras.

Running jhead on a JPEG file results in output like

Write a Python function gettime that reads a text like the one above, extracts, the time and date when the picture was taken (Date/Time), and returns the time and date information as two tuples of strings (HH,MM,SS) and (YYYY,MM,DD). The first tuple corresponds to the time HH:MM:SS (hours, minutes, seconds), whereas the second tuple corresponds to the date YYYY:MM:DD (year, month, day). (Hint: It might be convenient to split each line wrt. : into a list l, re-join l[1:], split wrt. whitespace, and then wrt. :.)

Write another Python function prefix that takes the time and date string tuples from gettime as input, together with the name of the image file, and prefixes the filename with the date and time. For example, if img_4978.jpg is the original filename, and the tuples returned from gettime are (18,10,03) and (2002,05,19), the returned string from prefix reads

If the filename already is on this form, no prefix should be added (i.e., the original filename is returned).

In case you have collections of images produced by digital cameras, the filenaming functionality presented in this exercises can be very convenient. The JPEG header is destroyed by many photo manipulation and viewing programs, so keeping the date in the filename preserves this important information. Since the JPEG header is easily destroyed, you should apply jhead and the renaming procedure to fresh files not yet being processed by programs.

Name of scriptfile: jpegrename.py (exercise class: Python)

### Week 6: Oct 19-23 (Class exercises, Python tasks)

#### 6.1 Implement a class for vectors in 3D

The purpose of this exercise is to program with classes and special methods. Create a class Vec3D with support for the inner product, cross product, norm, addition, subtraction, etc. The following application script demonstrates the required functionality:

We remark that class Vec3D is just aimed at being an illustrating exercise. Serious computations with a class for 3D vectors should utilize either a NumPy array (see Chapter 4), or better, the Vector class in the Scientific.Geometry.Vector module, which is a part of ScientificPython (see Chapter 4.4.1).

Name of scriptfile: vec3d.py (exercise class: Class)

#### 6.2 Extend the class from Exericse 6.1

Extend and modify the Vec3D class from Exericse 8.27 such that operators like + also work with scalars:

In the same way we should be able to do a-v, v-a, a*v, v*a, and v/a (a/v is not defined).

Name of scriptfile: vec3d_ext.py (exercise class: Class)

#### 6.3 Vectorize a constant function

does not work properly when x is a NumPy array. In that case the function should return a NumPy array with the same shape as x and with all entries equal to 3.0. Perform the necessary modifications such that the function works for both scalar types and NumPy arrays.

Name of scriptfile: vectorize_function.py (exercise class: Python)

#### 6.4 Vectorize a numerical integration rule

The integral of a function f(x) from x=a to x=b can be calculated numerically by the Trapezoidal rule:

where h equals (b-a)/(n-1). Implement this approximation in a Python function containing a straightforward loop.

The code will run slowly compared to a vectorized version. Make the vectorized version and introduce timings to measure the gain of vectorization. Use the functions

as test functions for the integration. (Hint: Implement f such that it operates on a vector x of all the evaluation points a+i*h, i=0. n-1.)

Name of scriptfile: vectorize_integration.py (exercise class: Python)

#### 6.5 Automate the creation of runtime examples

Create a script that takes the name of another script, an output filename, and arguments needed to run the other script, and based on these inputs generates a file containing the source code of the script and a runtime example in a special comment section at the bottom of the output file. For instance, running the script on the following file (bar.py):

should result in the following output (in assignment.txt):

Name of scriptfile: automate_runtime.py (exercise class: Python)

### Week 7: Oct 26-30 (Class exercises, Python tasks)

#### 7.1 Make a class for sparse vectors

The purpose of this exercise is to implement a sparse vector. That is, in a vector of length n, only a few of the elements are different from zero:

Implement a class SparseVec with the illustrated functionality. Hint: Store the nonzero vector elements in a dictionary.

Name of scriptfile: SparseVec.py (exercise class: Class)

#### 7.2 Assignment and in-place modifications of NumPy arrays

Consider the following script:

Explain why x, y, and z have the same values. How can be script be changed such that y and z get the intended values?

Name of scriptfile: NumPy_assignment.py (exercise class: Python)

#### 7.3 Implement Exercise 3.3 using NumPy arrays

Solve the same problem as in Exercise 3.3, but use NumPy and a vectorized algorithm. That is, generate two (long) random vectors of uniform integer numbers ranging from 1 to 6, find the entries that are 6 in one of the two arrays, count these entries and estimate the probability. Insert CPU-time measurements in the scripts and compare the plain Python loop and the random module with the vectorized version utilizing NumPy functionality.

Hint: You may use the following NumPy functions: random.randint, ==, +, >, and sum (read about them in the NumPy reference manual).

Name of scriptfile: dice2_NumPy.py (exercise class: Python)

#### 7.4 Implement Exercise 3.4 using NumPy arrays

Solve the same problem as in Exercise 3.4, but use NumPy and a vectorized algorithm. Generate a random vector of 4*n uniform integer numbers ranging from 1 to 6, reshape this vector into an array with four rows and n columns, representing the outcome of n throws with four dice, sum the eyes and estimate the probability. Insert CPU-time measurements in the scripts and compare the plain Python solution in Exercise 3.4 with the version utilizing NumPy functionality.

Hint: You may use the NumPy functions random.randint, sum, and < (read about them in the NumPy reference manual, and notice especially that sum can sum the rows or the columns in a two-dimensional array).

Name of scriptfile: dice4_NumPy.py (exercise class: Python)

#### 7.5 Process comma-separated numbers in a file

Suppose a spreadsheet program stores its table in a file row by row, but with comma-separated rows, as in this example:

Write a script that loads the text in the first column into a list of strings and the rest of the numbers into a two-dimensional NumPy array. Sum the elements in each row and write the result as

The script should of course treat any number of rows and columns in the file. Try to write the script in a compact way.

Name of scriptfile: process_spreadsheet.py (exercise class: Python)

### Week 8: Nov 2-6 (Class exercises, Python tasks)

#### 8.1 Matrix-vector multiply with NumPy arrays

Define a matrix and a vector, e.g.,

Use the NumPy reference manual to find a function that computes the standard matrix-vector product A times b (i.e., the vector whose i-th component is sum from j=0 to 2 of A[i,j]*b[j]).

Name of scriptfile: matvec.py (exercise class: Python)

#### 8.2 Replace lists by NumPy arrays

Modify the convert2.py script from Chapter 2.5 such that floating-point values are stored in NumPy arrays instead of plain Python lists.

Name of scriptfile: convert2_wNumPy.py (exercise class: Python)

#### 8.3 Equip class Grid2D with subscripting

Extend the Grid2D class from Chapter 4.3.5 with functionality such that one can extract the coordinates of a grid point i,j by writing:

when grid is some Grid2D object. Also make sure that assignment, as in

is an illegal option, i.e., we are not allowed to change the grid coordinates.

Name of scriptfile: Grid2D.py (exercise class: Class)

#### 8.4 Extend the functionality of class Grid2D

Consider class Grid2D from Chapter 4.3.5. Extend this class with the following features:

1. a __repr__ method for writing a string that can be used to recreate the grid object,
2. a __eq__ method for efficiently testing whether two grids are equal,
3. xmin, xmax, ymin, ymax read-only properties for extracting geometry information,
4. replace the dx and dy attributes by read-only properties with the same names.

Organize the additional code such that you can say

and get access to the extended Grid2D class, still under the name Grid2D. Hint: Use techniques from Chapter 8.6.13.

Also, you might want to consider the zen of the following code:

Name of scriptfile: Grid2D_add.py (exercise class: Class)

#### 8.5 Rock, Paper, Scissors

##### Description

Rock, paper, scissors, also know as roshambo, is a simple child's game that is frequently used to settle disputes. In the game, a rock breaks the scissors, the scissors cut the paper, and the paper covers the rock. Each option is equally likely to prevail over another. If the players choose the same object a draw is declared and the game is repeated until someone prevails. For more information than you ever thought it was possible to collect about rock, paper, scissors, check out the Web page of the World RPS Society. In this computerized version the human player competes against the computer which chooses a rock, paper, or scissors randomly. The game proceeds until the human player quits the game or until a predetermined score is reached (e.g., 11 pts.) at which time the final tally is displayed. Solutions with fewer numbers of if statements are considered more elegant.

##### Input

The human player enters the number of points required for a win. During the play of the game the human player selects whether to play a rock, paper, or scissors by using the keyboard. The human player may also end the game by pressing the Control-D sequence at any time. (Ending the game early does not allow a winner to be determined if the human player is ahead.)

##### Output

The program will display the winner of each roshambo round along with the running score. At the conclusion of the game, the computer will display the overall winner and the final score.

##### Sample session

This exercise is copied from openbookproject.net under the GNU Free Documentation License.

Name of scriptfile: roshambo.py

### Week 9: Nov 9-13 (Python tasks)

#### 9.1 Investigate the efficiency of various DAXPY implementations

A DAXPY operation performs the calculation u = a*x+y, where u, x, and y are vectors and a is a scalar. Implement the DAXPY operation in various ways:

(The name DAXPY originates from the name of the subroutine in the standard BLAS library offering this computation.)

Name of scriptfile: daxpy.py

#### 9.2 Investigate the efficiency of various DAXPY implementations cont.

This exercise is a continuation of exercise 9.1. This time, implement the following:

The Fortran code for DAXPY can be found here.

Name of scriptfile: daxpy_fortran.py

#### 9.3 Apply SWIG to an array class in C++

The purpose of this exercise is to wrap the MyArray from Chapter 10.2.3 such that MyArray objects can be used in Python in almost the same way as it is used in C++. Use SWIG to generate wrapper code. The code for MyArray can be found here.

Name of scriptfile: MyArray_wrap.py

#### 9.4 Literary Analysis

##### Description

Your English teacher has just asked you to write a paper comparing two of the works from the free, online literature library at Project Gutenberg. Since you are a computer scientist, you decide to put your skills to use. You plan to compare your two favorite works of classic literature in terms of the vocabulary used in each. Since this a bit outside the scope of the assignment as described by your English teacher, you ask for permission before you proceed. Intruiged by your proposal, your English teacher agrees and you are ready to go.

You plan to write a program that will take a text file as input and return a report listing alphabetically all the words in the file and the number of occurances of each.

This exercise is copied from openbookproject.net under the GNU Free Documentation License.

Name of scriptfile: gutenberg.py

#### 9.5 Math Quiz

##### Description

The following program runs a math quiz consisting of 10 multiplication problems involving operands between 1 and 10:

## From decimal to binary representation

In binary notation we have thus ( (417)_ <10>=(110110001)_2 ) since we have

$(110100001)_2 =1 imes2^8+1 imes 2^<7>+0 imes 2^<6>+1 imes 2^<5>+0 imes 2^<4>+0 imes 2^<3>+0 imes 2^<2>+0 imes 2^<2>+0 imes 2^<1>+1 imes 2^<0>.$

To see this, we have performed the following divisions by 2

 417/2=208 remainder 1 coefficient of ( 2^ <0>) is 1 208/2=104 remainder 0 coefficient of ( 2^ <1>) is 0 104/2=52 remainder 0 coefficient of ( 2^ <2>) is 0 52/2=26 remainder 0 coefficient of ( 2^ <3>) is 0 26/2=13 remainder 1 coefficient of ( 2^ <4>) is 0 13/2= 6 remainder 1 coefficient of ( 2^ <5>) is 1 6/2= 3 remainder 0 coefficient of ( 2^ <6>) is 0 3/2= 1 remainder 1 coefficient of ( 2^ <7>) is 1 1/2= 0 remainder 1 coefficient of ( 2^ <8>) is 1

## (5e) Is there any viable way to dual wield with strength and be optimal?

Polearm Master will almost always outshine dual wielding. It gives a bonus action attack, frees up a fighting style for fighters, grants attacks of opportunity against enemies that enter the area, and simplifies getting magical enhancements and weapon buffs.

For Dual Wielding to be better you need to use weapons that do something that the polearm master weapons can't. For strength to be better you need to use weapons that can't be used with dexterity. This pushes you into niche builds like throwing non-finesse weapons and dual wielding lances.

Before the Xanthar's Cavalier dual wielding a whip and non-reach weapon with Sentinel and Dual Wielder was an ok way of gaining control over a decent area, threatening an attack of opportunity against enemies leaving both 5ft and 10ft reach. The cavalier outshines that now, essentially getting the combined effects of Sentinel, Polearm Master with a quarterstaff, and dual wielding all wrapped in one in their 10th level ability.

The one thing that is easier with dual wielding is magic weapons if you have the feat. You can use any two magic one hand weapons you find. At least in the official adventures there are almost no magic polearms.

I would say the Strength Ranger would probably be the best case.

14 Dex for Medium Armor, and 14-16 Strength

The key of this build is that you abuse Hunter's Mark with your extra attacks, since it procs on every individual hit.

Dual Wield Hand Axes or Shortswords and after level 5, make sure you have your Hunter's Mark cast on the enemy, and with 16 strength, you're dealing..

3x (2d6 + 3) = 30 Average Damage.

Which means you're essentially mimicking 3 Greatsword Attacks per turn with your Hand Axes.

Also, going Monster Hunter will let you deal an extra 1d6 per turn as well if that tickles your fancy.

Polearm Master with dueling fighting style and a quarterstaff wielded one-handed comes out ahead in AC and damage and utility:

+2 AC from shield, 35 average damage. 2x (2d6 + 2 + 3) + 1d4 + 1d6 + 2 + 3

Polearm Master with a polearm and defense fighting style comes out ahead in damage and reach and utility:

+1 AC from defense fighting style. 33 average damage. 2x (1d10 + 1d6 + 3) + 1d4 + 1d6 + 3

With a polearm wielded two-handed you still have a free hand to cast ranger spells.

In both cases you get the polearm master attack of opportunity.

One build worth mentioning is Barbarian 2+/Rogue. Recklessly attacking with a finesse weapon using strength gives reliable advantage and access to sneak attack. Dual wielding weapons gives an extra opportunity to land sneak attack, or just another attack with advantage for damage. Rapier + Whip is a nice combination to have both piercing and slashing damage and get attacks of opportunity against enemies leaving either a 5ft or 10ft reach.

Edit: you're stuck with scimitars/short swords unless you get Dual Wielder

I've been doing some math with my 8th-level PC with Two-Weapon Fighting Fighting Style and 16 Str (MAD multiclass). It's slightlu more valuable to up Str than take Dual Wielder since d6+1 is pretty much equal to d8 on average and upping Str gives you a better chance to hit. I think the difference is probably negligible. As in, if you really like swords more than handaxes, it's worth sacrificing the slightly less DPR. For a barbarian like you suggested, it might be worth the feat for extra bit of AC and they're probably hitting often anyways with Reckless Attack.

I haven’t been able to figure this one out. I feel like TWF being tied to your bonus action holds it back, especially with feats like polearm master and many class features on BA (second wind, rage, Paladin and Ranger spells, cunning action).

One thing to like about a TWF build is that it doesn’t need feats to support it. If you’re in a game where feats are not allowed (uncommon but possible), it can shine a little better.

With feats, you can use your first ASI for something else that’s flavorful or fits your build, like heavy armor master, lucky, etc.. Unless you’re a fighter, your second ASI isn’t until level 8, which is a lot of play time at best and many games end before then or not long after.

This isn’t quite what you’re looking for, but tortle monks can go STR instead of DEX. While monks don’t do TWF, they’re similar in practice, with more, smaller hits.

Who says (tortle) monks don't go TWF? Best greetings, Leonardo, Michelangelo and Raphael (Donatello is indisposed)

Its pretty munchkin, but you could dual wield lances according to the rules as long as you have a mount. Making cavalier probably ideal or you could maybe go a small race combined with beastmaster to ride a medium size mount.

Alternatively, as a cavalier you could have a lance on one hand and a d8 weapon of choice in the other. This way you can take advantage of the abilities that require you to be within 5 ft of enemies by first charging with your lance and then following up with your long sword.

Also, its hard to explain concisely, but you can take advantage of the cavalier’s abilities with a lance and d8 weapon better than you could with 2 lances. Like being able to attack something within 5ft of you without the disadvantage that a lance would impose.

For the cavalier route, I’d take Dual Wielder and Mounted Combatant for sure. With your extra feats, you can either ASI or get stuff to make you tankier like Tough, Resilient, and/or Heavy Armor Master. Race would be v. Human or a +2 str race like a half orc.

On the otherhand, if you don’t care for the cavaliers tricks, you could just simply put a half orc Champion fighter on a horse and dual wield 2d12 lances with advantage from mounted combat and crit on 19s and 20s as soon as level 4.

Lances aren't light weapons, you can't two-weapon fight with them without Dual Wielder, which is unavailable to a 3rd level half-orc Champion fighter.

Iɽ say go barbarian. Dual wield extends the number of times you can apply your rage damage bonus.

An option that springs to mind is a paladin. Go main stat strength with double longswords so you can make dex your dumpstat and go absolutely ham on things from level 11 onward.

Take dual wielder for the +1 ac, combine with your fighting style defense you will be as tanky as if you had a shield

Polearm Master with dueling fighting style and a quarterstaff wielded one-handed comes out ahead.

+2 AC from a shield, 30.5 average damage. 1d6 + 2 + 5 Str, 1d6 + 2 + 5 Str, 1d4 + 2 + 5 Str

+2 AC from dual wielder and defense fighting style. 23.5 average damage. 1d8 + 5 Str, 1d8 + 5 Str, 1d8

Plus you get the polearm master attack of opportunity. Plus you get a holy symbol on your shield so you can actually cast spells without juggling weapons.

Even with defense fighting style (+3 AC) Polearm Master does more damage (24.5 avg), and has the flexibility to switch to a two-handed polearm without losing the benefit of their fighting style.

Edit: and the polearm master can be a hexblade to use charisma with their quarterstaff to be SAD, and their quarterstaff can be their arcane focus for warlock spellcasting.

Yes. It's called Pole Arm Master.

The optimal point of dual wielding, is just like 1-handing. You have the option to change to the situation. Unlike a great weapon, you can carry a few different 1-handers without them getting in the way.

Such is the greatness of the warlock pact of the blade. Vulnerable to blunt? ya got it. Slashing? got that too.

When it comes to magic weapons, damn the attunement to only 3 at a time, but you can dual wield and grab appropriate weapons. You can even carry more, just need a short rest(?) to attune to the battle you know is coming. For instance that frostbrand dagger that you never use? Or the specific mace of smiting?

Sure you'll be slightly under damage when compared to the munchkins of PoleArms, but they don't carry multiple types of weapons to bypass resistance and the like. Bringing a weapon the mobs are vulnerable to is the Optimal use of dual wielding. Though, much like a wizard, a master of battle knows intelligence is needed.

For those that don't know, Vulnerability doubles the damage, so that 1d4 piercing dagger that you saved, now does 12-18(with +5 STR) if they are vulnerable to piercing. New target vulnerable to Fire as well? Well now your dual-wielding two vulnerabilities. They don't stack, but multiple strikes are still multiple strikes.

Its a costly endeavor to be sure, but such is the path of the prepared warrior. The Jack of all Weapons if you would.

## Steps in Period Plan

1. Introduction

• Greetings
• Testing / re-teaching previous knowledge (Game / situation / probing questions)
• Introduction to concept through daily life situation
• Announcement of the topic
• Scope of the topic

2. Presentation and Discussion

• Discussion on key terminology and key concepts
• Activities (Whole class / group / individual) to comprehend the concepts
• Summing up by the teacher

3. Problem Solving

• Solving by the teacher with discussion and help of students
• Solving problems by the students in groups / individual
• Discussion on mistakes done by the students and doubt clarification

4. Recapitulation: Revision / summing up of concepts taught in the period
5. Home work: Suggesting problems in exercises or problems created by the teacher (Every teacher must keep these steps and concepts scheduled, in teaching in every period, but need not to write a detailed period plan)

*Disclaimer: We have published the above information for reference Purpose only, For any changes on the content we refer to visit the Official website to get the latest & Official details, and we are not responsible for anything

## 12.5E: Exercises - Mathematics

This online/interactive visual math addition, will create 1 digit by 1 digit (1x1) picture only equations, and it will automatically graded/scored your results in a printable worksheet. No Timed-Test .

• Online - Visual Math - No Carryovers
• Online - Visual Math - Carryovers
• Online - Visual Math - Addition: 0 to 5
• Online - Visual Math - Addition: 5 to 10
• Online - Visual Math - Addition: 0 to 10
• Online - Visual Math - Addition: 0 to 18
• Online - Visual Math - Addition: 10 to 18

This math worksheet maker will create a horizontal visual math addition, 1 digit by 1 digit (1x1) picture only equations with the handwriting lines.

This math worksheet maker will create a horizontal visual math addition, 1 digit by 1 digit (1x1) picture only equations without the handwriting lines.

This worksheet generator will create your own customized/personalized visual math addition worksheet. You enter your own math problems to create your own picture only printable worksheet. Addend ranges between 0 and 20 only.

This online/interactive math addition generator will provides plenty of online math practice, boost test scores and prepare the child/children to meet the Kindergarten, Grade 1, and Grade 2 curriculum standards. This online/interactive math addition, will create the vertical 1 digit by 1 digit (1x1) equations with an option of timed test, and it will automatically graded/scored your results in a printable worksheet.

Type of online math problems:

• Online - Addition - No Carryovers
• Online - Addition - Carryovers

This printable basic math addition worksheet generator will provides plenty of math practice, boost test scores and prepare the child/children to meet the Kindergarten, Grade 1, and Grade 2 curriculum standards. This math worksheet maker will create the vertical math addition, 1 digit by 1 digit (1x1) equations with handwriting lines.

This printable basic math addition worksheet generator will provides plenty of math practice, boost test scores and prepare the child/children to meet the Kindergarten, Grade 1, and Grade 2 curriculum standards. This math worksheet maker will create the vertical math addition, 1 digit by 1 digit (1x1) equations.

This worksheet generator will create your own customized/personalized addition worksheet. You enter your own vertical math problems in a printable worksheet. Maximum 5 digits x 5 digits (5x5).

This online/interactive math addition generator will provides plenty of online math practice, boost test scores and prepare the child/children to meet the Grade 1, Grade 2, and Grade 3 curriculum standards. This online/interactive math addition, will create the vertical 2 digits by 1 digit (2x1) and 1 digit by 2 digits (1x2) equations with an option of timed test, and it will automatically graded/scored your results in a printable worksheet.

Type of online math problems:

• Addition - No Carryovers (2 Digits - Top Only)
• Addition - No Carryovers (2 Digits - Bottom Only)
• Addition - No Carryovers (2 Digits - Random)
• Addition - Carryovers (2 Digits - Top Only)
• Addition - Carryovers (2 Digits - Bottom Only)
• Addition - Carryovers (2 Digits - Random)

This printable basic math addition worksheet generator will provides additional of math practice, boost test scores and prepare the child/children to meet the Grade 1, Grade 2, and Grade 3 curriculum standards. This math worksheet maker will create the vertical math addition, 2 digits by 1 digit (2x1), and 1 digit by 2 digits (1x2) equations with handwriting lines.

(2 Digits - Top Only) (2 Digits - Bottom Only) (2 Digits - Random) (2 Digits - Top Only) (2 Digits - Bottom Only) (2 Digits - Random)

This printable basic math addition worksheet generator will provides additional of math practice, boost test scores and prepare the child/children to meet the Grade 1, Grade 2, and Grade 3 curriculum standards. This math worksheet maker will create the vertical math addition, 2 digits by 1 digit (2x1), and 1 digit by 2 digits (1x2) equations without the handwriting lines.

(2 Digits - Top Only) (2 Digits - Bottom Only) (2 Digits - Random) (2 Digits - Top Only) (2 Digits - Bottom Only) (2 Digits - Random)

This worksheet generator will create your own customized/personalized addition worksheet. You enter your own vertical math problems in a printable worksheet. Maximum 5 digits x 5 digits (5x5).

This online/interactive math addition generator will provides plenty of online math practice, boost test scores and prepare the child/children to meet the Kindergarten, Grade 1, and Grade 2 curriculum standards. This online/interactive math addition, will create the horizontal 1 digit by 1 digit (1x1) equations with an option of timed test, and it will automatically graded/scored your results in a printable worksheet.

• Online - Addition - No Carryovers
• Online - Addition - Carryovers

This printable basic math addition worksheet generator will provides plenty of math practice, boost test scores and prepare the child/children to meet the Kindergarten, Grade 1, and Grade 2 curriculum standards. This math worksheet maker will create the horizontal math addition, 1 digit by 1 digit (1x1) equations with handwriting lines.

This printable basic math addition worksheet generator will provides plenty of math practice, boost test scores and prepare the child/children to meet the Kindergarten, Grade 1, and Grade 2 curriculum standards. This math worksheet maker will create the horizontal math addition, 1 digit by 1 digit (1x1) equations without handwriting lines.

This worksheet generator will create your own customized/personalized addition worksheet. You enter your own vertical math problems in a printable worksheet. Maximum 5 digits x 5 digits (5x5).

## Search results

### MYP Mathematics 4&5 Extended Enhanced Online Book

Fully comprehensive and matched to the revised MYP Mathematics framework

Price: £42.99 +VAT

### MYP Mathematics 4&5 Extended Print and Enhanced Online Book Pack

Fully comprehensive and matched to the revised MYP Mathematics framework

Price: £42.99 +VAT

### MYP Mathematics 4&5 Standard Enhanced Online Book

Fully comprehensive and matched to the revised MYP Mathematics framework

Price: £45.99 +VAT

### MYP Mathematics 4&5 Standard Print and Enhanced Online Book Pack

Fully comprehensive and matched to the revised MYP Mathematics framework

Price: £45.99 +VAT

### MYP Mathematics 3: Print and Enhanced Online Course Book Pack

Build mathematical understanding and conceptual connections

Author Rose Harrison, Author David Weber, Author Talei Kunkel, and Author Fatima Remtulla

Price: £37.99 +VAT

### MYP Mathematics 2: Print and Enhanced Online Course Book Pack

Build mathematical understanding and conceptual connections

Author David Weber, Author Talei Kunkel, Author Alexandra Martinez, and Author Rebecca Shultis

Price: £37.99 +VAT

### MYP Mathematics 2: Enhanced Online Course Book

Build mathematical understanding and conceptual connections

Author David Weber, Author Talei Kunkel, Author Alexandra Martinez, and Author Rebecca Shultis

Digital Licence Key | 22/11/2018

Price: £37.99 +VAT

### MYP Mathematics 3: Enhanced Online Course Book

Build mathematical understanding and conceptual connections

Author Rose Harrison, Author David Weber, Author Talei Kunkel, and Author Fatima Remtulla

Digital Licence Key | 22/11/2018

Price: £37.99 +VAT

### MYP Mathematics 1: Print and Enhanced Online Course Book Pack

Build mathematical understanding and conceptual connections

Author David Weber, Author Talei Kunkel, and Author Harriet Simand

Price: £37.99 +VAT

### MYP Mathematics 1: Enhanced Online Course Book

Build mathematical understanding and conceptual connections

Author David Weber, Author Talei Kunkel, and Author Harriet Simand

Digital Licence Key | 11/10/2018

Price: £37.99 +VAT

Price and stock details listed on this site are as accurate as possible, and subject to change. Occasionally, due to the nature of some contractual restrictions, we are unable to ship to some territories for further details on shipping restrictions go to our Help section.