ENGR-131 Name : _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Spring 2020 first last
Your Magic Number is where is the number of letters in your first name and is the number of letters in your second name. Record it here before you start.
M = _ _ _ _
Instructions: Complete each of the five questions. Work must be your own. No collaboration allowed.
Due Date: PDF must be uploaded by Tuesday June9 before 11:59PM
1. Numerical Exploration: Primes, Semiprimes and Palindromes
Here are two free methods to use in your solution.
import math
def is_prime(n):
if n<2: return 0
for d in range(2, round(math.sqrt(n)) + 1):
XXXXXXXXXXif not n % d: return 0
return 1
def is_palindrome(n):
if n < 0: return 0 # don’t check negative numbers
forward_string = str(n)
backward_string = forward_string[::-1]
return forward_string == backward_string
a. Generate a sorted list P1 of all the primes up to M, your magic number. P1 = [2, 3, 5, …]
How many primes are in your list P1? Ans: _ _ _
. A semiprime (or biprime) is a positive integer n than can be written as the product of two primes, so where and are both primes. The two primes can be the same, so the first semiprime is 4.
Using a set comprehension generate all the semiprimes P2 less than or equal to M.
Tip: Easiest with two for loops and one filter (if statement) in your initial set comprehension.
Then convert the set to a list using list() and sort it.
How many semiprimes are in your list P2? Ans: _ _ _
c. Hypothesis: Every positive integer n is the sum of a prime and a semiprime, so we can write
where , and are all primes. This can't quite be true since the smallest prime is 2 and the smallest semiprime is 4, so we must exclude all numbers less than 6.
List any additional numbers that cannot be represented in this form checking all the way up to M.
The exceptions are: 1, 2, 3, 4, 5 and _ _ _ _ _ _ _ _
d. Find all the three-digit, palindromic semiprimes. How many are there? _ _ _ _ _
e. Find all the four-digit, palindromic semiprimes. How many are there? _ _ _ _ _
2. Files and Searching Files
Download the text file named Baskervilles.txt which contains the complete test for Arthur Conan Doyle's "The Hound of the Baskervilles". File was obtained from Project Gutenberg.
a. We are going to study the words in this document. But first, complete this method which given a word, converts the word to all upper case and tosses away any characters that are not alphabetical.
However, do include any dashes! "-" These may occur in hyphenated words.
The method returns the cleaned-up word. Must use a single if statement and the keyword or.
Examples: cat's CATS, Forget-me-not FORGET-ME-NOT
def clean_up(word):
w = ""
for char in word.upper():
return w
. Create an empty dictionary named D. Open your text file and using nested for loops read in every line and word in the file. The split() command will help convert a line to a list of words. Clean up each word (as you find it) and name it WORD. Add each WORD to the dictionary D, being sure to update the value to keep count of the number of occu
ences. The get() method may help. Alert: This process may have created the empty word ''. Delete that from your dictionary using del.
Your magic letter is the first letter in your first name (in caps). My Magic Letter is: ____
c. Find the 3-letter word that starts with your magic letter and has the greatest frequency. If there are none, then allow more than 3 letters. __ __ __
d. How many words start with your magic letter and only appear once in the story? __ __ __
e. How many words appear 100 or more times in the story? __ __ __
3. Read and Plot Simulated Data Provided in a csv file.
a. Choose your datafile.
If your last name starts with A-G you must choose data1.csv
If your last name starts with H-O you must choose data2.csv
If your last name starts with P-S you must choose data3.csv
If your last name starts with T-Z you must choose data4.csv
I am using the data file numbered : ____
Each data file contains two columns of data. The first column is the time t in minutes. The second column is the intensify of a function that seems to fit a biexponential curve.
Alert: There is a header row!
a. Using csv.reader(), read in all the data. Be sure to skip the header row. Append all the time values to a list named time. Append all the y-values to a list named y.
Print out the sum of the y-values. _ _ _ _ _ _ _ _ _ _
. Find the biggest y-value. Biggest y is: _ _ _ _ _ _ _ _ _ _
c. Complete this method to automatically find the point with the maximum y-value. You should already have two lists named time and y.
tmax, ymax = 0, 0 # stub values
for n in range(len(time)):
# get the next time and y values
# test if this y is bigger than ymax (so far) and update
d. Using matplotlib, create a plot of your data points. Show each point as a circle with a blue outline and filled with yellow.
e. Add the title "Biexponential Data". Fill in the maximum point in red and make it a little larger than the other data points.
Paste your completed plot to the right.
4. Curve-Fitting your Data with a Biexponential
Your data from the previous exercise is exactly fitted by a biexponential curve of the form:
a. You should already have two lists named time and y containing the 101 data points from the previous exercise. Be sure to complete that exercise before attempting this one.
Write the code to import curve_fit from the scipy module and also import numpy and give it the shorter name np.
. Complete the method f(t,*p) so it returns the value of the biexponential function at time t:
Must use the numpy module for the exponential function, and not the math module.
def f(t, *p):
c. Complete this single line by calling curve_fit to return the optimal parameters popt and the covariance pcov for these parameters. The data points are in the lists named time and y containing. Explicitly provide a guess for p0.
popt, pcov =
d. Record the best-fit parameters for your data here.
= _ _ _ _ = _ _ _ _ = _ _ _ _ = _ _ _ _
Hint: All four parameters will be integers, and some are negative. You will need to try other initial guesses than p0=[1, 1, 1, 1] if this default guess does not produce an exact integer fit with a covariance matrix with all elements equal to zero.
5. A Class of Animals! (5 points)
After reading through chapter 11, you should be easily able to complete this problem. Animals need food. Let's create a dictionary describing the available food items and their nutritional value.
import random
food_value = {} # dictionary of food items and their life-energy value
plants = {"grass":1, "weeds":1, "ca
ots":4, "lettuce":2, "nut":5}
meat = {"hot dog":10, "steak":20, "fish":15, "burger":15}
1. The dictionary named food_value is cu
ently empty. Add some code so it holds the values for all the plants and meats. Must not use any :'s in your answer. OK to use two statements.
Each animal has a name and a life_energy. The animal will die if its life energy falls to zero.
class Animal(object):
def __init__(self, name=None, life_energy=10):
XXXXXXXXXXself.name = name;
XXXXXXXXXXself.life_energy = life_energy
2. Complete the eat() method, which is inside the class body. When the food item is eaten, the animal's life_energy is increased by the amount recorded in the dictionary food_value.
def eat(self, food): # An animal can eat food.Increase its life_energy.
3. Complete the is_alive() method, which is inside the class body. An animal is only alive provided its life_energy > 0. Must not use an if statement. Go directly to the return statement.
def is_alive(self): # Is the animal still alive?
Finding food requires some effort or cost. This method decreases the animal's life_energy when it exerts an effort. Given for free. The max command keeps the life-energy from becoming negative. Given for free.
# decreases the life_energy by the cost of an effort.
def work(self, cost):
XXXXXXXXXXself.life_energy = max(0, self.life_energy - cost)
if __name__ == "__main__":
# Demo of the Animal class
Enter your magic number from Question 1
M = _ _ _ _
random.seed(M)
# 4. Construct a goat named "Billy" and give Billy 50 life units.
goat =
In the for loop below, your goat Billy goes searching for food once each day of the week. This always costs him 10 life_energy units for the effort. Each day he encounters one random item of food, gaining its life energy but costing ten units for the effort