-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from rickecon/chaps
Merging
- Loading branch information
Showing
51 changed files
with
10,176 additions
and
116 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
# advanced_numpy.py | ||
"""Python Essentials: Advanced NumPy. | ||
<Name> | ||
<Class> | ||
<Date> | ||
""" | ||
import numpy as np | ||
from sympy import isprime | ||
from matplotlib import pyplot as plt | ||
|
||
|
||
def prob1(A): | ||
"""Make a copy of 'A' and set all negative entries of the copy to 0. | ||
Return the copy. | ||
Example: | ||
>>> A = np.array([-3,-1,3]) | ||
>>> prob4(A) | ||
array([0, 0, 3]) | ||
""" | ||
raise NotImplementedError("Problem 1 Incomplete") | ||
|
||
|
||
def prob2(arr_list): | ||
"""return all arrays in arr_list as one 3-dimensional array | ||
where the arrays are padded with zeros appropriately.""" | ||
raise NotImplementedError("Problem 2 Incomplete") | ||
|
||
|
||
def prob3(func, A): | ||
"""Time how long it takes to run func on the array A in two different ways, | ||
where func is a universal function. | ||
First, use array broadcasting to operate on the entire array element-wise. | ||
Second, use a nested for loop, operating on each element individually. | ||
Return the ratio showing how many times faster array broadcasting is than | ||
using a nested for loop, averaged over 10 trials. | ||
Parameters: | ||
func -- array broadcast-able numpy function | ||
A -- nxn array to operate on | ||
Returns: | ||
num_times_faster -- float | ||
""" | ||
raise NotImplementedError("Problem 3 Incomplete") | ||
|
||
|
||
def prob4(A): | ||
"""Divide each row of 'A' by the row sum and return the resulting array. | ||
Example: | ||
>>> A = np.array([[1,1,0],[0,1,0],[1,1,1]]) | ||
>>> prob6(A) | ||
array([[ 0.5 , 0.5 , 0. ], | ||
[ 0. , 1. , 0. ], | ||
[ 0.33333333, 0.33333333, 0.33333333]]) | ||
""" | ||
raise NotImplementedError("Problem 4 Incomplete") | ||
|
||
|
||
# this is provided for problem 5 | ||
def LargestPrime(x, show_factorization=False): | ||
# account for edge cases. | ||
if x == 0 or x == 1: | ||
return np.nan | ||
|
||
# create needed variables | ||
forced_break = False | ||
prime_factors = [] # place to store factors of number | ||
factor_test_arr = np.arange(1, 11) | ||
|
||
while True: | ||
# a factor is never more than half the number | ||
if np.min(factor_test_arr) > (x // 2) + 1: | ||
forced_break = True | ||
break | ||
if isprime(x): # if the checked number is prime itself, stop | ||
prime_factors.append(x) | ||
break | ||
|
||
# check if anythin gin the factor_test_arr are factors | ||
div_arr = x / factor_test_arr | ||
factor_mask = div_arr - div_arr.astype(int) == 0 | ||
divisors = factor_test_arr[factor_mask] | ||
if divisors.size > 0: # if divisors exist... | ||
if ( | ||
divisors[0] == 1 and divisors.size > 1 | ||
): # make sure not to select 1 | ||
i = 1 | ||
elif ( | ||
divisors[0] == 1 and divisors.size == 1 | ||
): # if one is the only one don't pick it | ||
factor_test_arr = factor_test_arr + 10 | ||
continue | ||
else: # othewise take the smallest divisor | ||
i = 0 | ||
|
||
# if divisor was found divide number by it and | ||
# repeat the process | ||
x = int(x / divisors[i]) | ||
prime_factors.append(divisors[i]) | ||
factor_test_arr = np.arange(1, 11) | ||
else: # if no number was found increase the test_arr | ||
# and keep looking for factors | ||
factor_test_arr = factor_test_arr + 10 | ||
continue | ||
|
||
if show_factorization: # show entire factorization if desired | ||
print(prime_factors) | ||
if forced_break: # if too many iterations break | ||
print(f"Something wrong, exceeded iteration threshold for value: {x}") | ||
return 0 | ||
return max(prime_factors) | ||
|
||
|
||
def prob5(arr, naive=False): | ||
"""Return an array where every number is replaced be the largest prime | ||
in its factorization. Implement two methods. Switching between the two | ||
is determined by a bool. | ||
Example: | ||
>>> A = np.array([15, 41, 49, 1077]) | ||
>>> prob4(A) | ||
array([5,41,7,359]) | ||
""" | ||
raise NotImplementedError("Problem 5 Incomplete") | ||
|
||
|
||
def prob6(x, y, z, A, optimize=False, split=True): | ||
"""takes three vectors and a matrix and performs | ||
(np.outer(x,y)*z.reshape(-1,1))@A on them using einsum.""" | ||
raise NotImplementedError("Problem 6 part 1 Incomplete") | ||
|
||
|
||
def naive6(x, y, z, A): | ||
"""uses normal numpy functions to do what prob5 does""" | ||
raise NotImplementedError("Problem 6 part 2 Incomplete") | ||
|
||
|
||
def prob7(): | ||
"""Times and creates plots that generate the difference in | ||
speeds between einsum and normal numpy functions | ||
""" | ||
raise NotImplementedError("Problem 7 Incomplete") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
A b C | ||
d E f |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
Ab Cd | ||
Ef Gh | ||
Ij Kl |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
# exceptions_fileIO.py | ||
"""Python Essentials: Exceptions and File Input/Output. | ||
<Name> | ||
<Class> | ||
<Date> | ||
""" | ||
|
||
from random import choice | ||
|
||
|
||
# Problem 1 | ||
def arithmagic(): | ||
""" | ||
Takes in user input to perform a magic trick and prints the result. | ||
Verifies the user's input at each step and raises a | ||
ValueError with an informative error message if any of the following occur: | ||
The first number step_1 is not a 3-digit number. | ||
The first number's first and last digits differ by less than $2$. | ||
The second number step_2 is not the reverse of the first number. | ||
The third number step_3 is not the positive difference of the first two numbers. | ||
The fourth number step_4 is not the reverse of the third number. | ||
""" | ||
|
||
step_1 = input( | ||
"Enter a 3-digit number where the first and last " | ||
"digits differ by 2 or more: " | ||
) | ||
step_2 = input( | ||
"Enter the reverse of the first number, obtained " | ||
"by reading it backwards: " | ||
) | ||
step_3 = input("Enter the positive difference of these numbers: ") | ||
step_4 = input("Enter the reverse of the previous result: ") | ||
print(str(step_3), "+", str(step_4), "= 1089 (ta-da!)") | ||
|
||
|
||
# Problem 2 | ||
def random_walk(max_iters=1e12): | ||
""" | ||
If the user raises a KeyboardInterrupt by pressing ctrl+c while the | ||
program is running, the function should catch the exception and | ||
print "Process interrupted at iteration $i$". | ||
If no KeyboardInterrupt is raised, print "Process completed". | ||
Return walk. | ||
""" | ||
|
||
walk = 0 | ||
directions = [1, -1] | ||
for i in range(int(max_iters)): | ||
walk += choice(directions) | ||
return walk | ||
|
||
|
||
# Problems 3 and 4: Write a 'ContentFilter' class. | ||
class ContentFilter(object): | ||
"""Class for reading in file | ||
Attributes: | ||
filename (str): The name of the file | ||
contents (str): the contents of the file | ||
""" | ||
|
||
# Problem 3 | ||
def __init__(self, filename): | ||
"""Read from the specified file. If the filename is invalid, prompt | ||
the user until a valid filename is given. | ||
""" | ||
|
||
# Problem 4 --------------------------------------------------------------- | ||
def check_mode(self, mode): | ||
"""Raise a ValueError if the mode is invalid.""" | ||
|
||
def uniform(self, outfile, mode="w", case="upper"): | ||
"""Write the data to the outfile with uniform case. Include an additional | ||
keyword argument case that defaults to "upper". If case="upper", write | ||
the data in upper case. If case="lower", write the data in lower case. | ||
If case is not one of these two values, raise a ValueError.""" | ||
|
||
def reverse(self, outfile, mode="w", unit="word"): | ||
"""Write the data to the outfile in reverse order. Include an additional | ||
keyword argument unit that defaults to "line". If unit="word", reverse | ||
the ordering of the words in each line, but write the lines in the same | ||
order as the original file. If units="line", reverse the ordering of the | ||
lines, but do not change the ordering of the words on each individual | ||
line. If unit is not one of these two values, raise a ValueError.""" | ||
|
||
def transpose(self, outfile, mode="w"): | ||
"""Write a transposed version of the data to the outfile. That is, write | ||
the first word of each line of the data to the first line of the new file, | ||
the second word of each line of the data to the second line of the new | ||
file, and so on. Viewed as a matrix of words, the rows of the input file | ||
then become the columns of the output file, and viceversa. You may assume | ||
that there are an equal number of words on each line of the input file. | ||
""" | ||
|
||
def __str__(self): | ||
"""Printing a ContentFilter object yields the following output: | ||
Source file: <filename> | ||
Total characters: <The total number of characters in file> | ||
Alphabetic characters: <The number of letters> | ||
Numerical characters: <The number of digits> | ||
Whitespace characters: <The number of spaces, tabs, and newlines> | ||
Number of lines: <The number of lines> | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
Hello, | ||
World! |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
# matplotlib_intro.py | ||
"""Python Essentials: Intro to Matplotlib. | ||
<Name> | ||
<Class> | ||
<Date> | ||
""" | ||
|
||
|
||
# Problem 1 | ||
def var_of_means(n): | ||
"""Create an (n x n) array of values randomly sampled from the standard | ||
normal distribution. Compute the mean of each row of the array. Return the | ||
variance of these means. | ||
Parameters: | ||
n (int): The number of rows and columns in the matrix. | ||
Returns: | ||
(float) The variance of the means of each row. | ||
""" | ||
raise NotImplementedError("Problem 1 Incomplete") | ||
|
||
|
||
def prob1(): | ||
"""Create an array of the results of var_of_means() with inputs | ||
n = 100, 200, ..., 1000. Plot and show the resulting array. | ||
""" | ||
raise NotImplementedError("Problem 1 Incomplete") | ||
|
||
|
||
# Problem 2 | ||
def prob2(): | ||
"""Plot the functions sin(x), cos(x), and arctan(x) on the domain | ||
[-2pi, 2pi]. Make sure the domain is refined enough to produce a figure | ||
with good resolution. | ||
""" | ||
raise NotImplementedError("Problem 2 Incomplete") | ||
|
||
|
||
# Problem 3 | ||
def prob3(): | ||
"""Plot the curve f(x) = 1/(x-1) on the domain [-2,6]. | ||
1. Split the domain so that the curve looks discontinuous. | ||
2. Plot both curves with a thick, dashed magenta line. | ||
3. Set the range of the x-axis to [-2,6] and the range of the | ||
y-axis to [-6,6]. | ||
""" | ||
raise NotImplementedError("Problem 3 Incomplete") | ||
|
||
|
||
# Problem 4 | ||
def prob4(): | ||
"""Plot the functions sin(x), sin(2x), 2sin(x), and 2sin(2x) on the | ||
domain [0, 2pi], each in a separate subplot of a single figure. | ||
1. Arrange the plots in a 2 x 2 grid of subplots. | ||
2. Set the limits of each subplot to [0, 2pi]x[-2, 2]. | ||
3. Give each subplot an appropriate title. | ||
4. Give the overall figure a title. | ||
5. Use the following line colors and styles. | ||
sin(x): green solid line. | ||
sin(2x): red dashed line. | ||
2sin(x): blue dashed line. | ||
2sin(2x): magenta dotted line. | ||
""" | ||
raise NotImplementedError("Problem 4 Incomplete") | ||
|
||
|
||
# Problem 5 | ||
def prob5(): | ||
"""Visualize the data in FARS.npy. Use np.load() to load the data, then | ||
create a single figure with two subplots: | ||
1. A scatter plot of longitudes against latitudes. Because of the | ||
large number of data points, use black pixel markers (use "k," | ||
as the third argument to plt.plot()). Label both axes. | ||
2. A histogram of the hours of the day, with one bin per hour. | ||
Label and set the limits of the x-axis. | ||
""" | ||
raise NotImplementedError("Problem 5 Incomplete") | ||
|
||
|
||
# Problem 6 | ||
def prob6(): | ||
"""Plot the function g(x,y) = sin(x)sin(y)/xy on the domain | ||
[-2pi, 2pi]x[-2pi, 2pi]. | ||
1. Create 2 subplots: one with a heat map of g, and one with a contour | ||
map of g. Choose an appropriate number of level curves, or specify | ||
the curves yourself. | ||
2. Set the limits of each subplot to [-2pi, 2pi]x[-2pi, 2pi]. | ||
3. Choose a non-default color scheme. | ||
4. Include a color scale bar for each subplot. | ||
""" | ||
raise NotImplementedError("Problem 6 Incomplete") |
Oops, something went wrong.