Python homework 1
From four_to_eighty above, select only the numbers divisible by 6 and assign them to a new list named div_by_6. You may want to use a for loop with the list four_to_eighty as shown below. Inside the loop, make use of % and == operators to test the divisibility of each element in the list and then append the number to the list. Start with the code below # An empty list named div_by_6 div_by_6 = list() for number in four_to_eighty: In [26]:
div_by_6 = list() for number in four_to_eighty: if (number%6) == 0: div_by_6.append(number)
Write a function that checks if an integer is a prime number or not. The function will return True if the integer is a prime, False otherwise. If the input is not an integer greater than 1, the function displays a message, "___ is not an integer greater than 1." and returns nothing.
-
Write a function named get_div3or4 that takes a list of integers and returns a list of elements that are divisible by three or four. The header of the function is specified below. # Start with the function below def get_div3or4(inList): outList = list()
def get_div3or4(inList): outlist = list() for number in inList: if (number%3==0) or (number%4==0): outlist.append(number) return outlist
Create a matrix (two-dimentional numpy array) of even numbers from 2 through 60 with 6 rows and 5 columns. The values within the matrix should increase row-wise. Assign it to a variable even_matrix. Create another matrix of odd numbers from 1 through 59 with 6 rows and 5 columns. The values within the matrix should increase row-wise . Assign it to a variable odd_matrix. Subtract odd_matrix from even_matrix, and store it in a variable named diff_mat. Calculate the sum of all elements in diff_mat and store it to sum_of_differences. Combine the rows of odd_matrix with that of even_matrix (i.e., the resulting matrix will have 12 rows and 5 columns), showing odd_matrix on top. Assign the result to a variable combined_by_row. Hint: Use numpy's append() function and specify the axis argument. Combine the columns of odd_matrix with that of even_matrix (i.e., the resulting matrix will have 6 rows and 10 columns), showing odd_matrix on the left. Assign the result to a variable combined_by_col.
even_matrix = np.array(range(2,61,2)).reshape(6,5) odd_matrix = np.array(range(1,60,2)).reshape(6,5) diff_mat = even_matrix-odd_matrix sum_of_difference = diff_mat.sum() combined_by_row = np.append(odd_matrix,even_matrix, axis=0) combined_by_col = np.append(odd_matrix,even_matrix, axis=1)
Write your own median function named my_median for a list. For a list with odd number of elements, the median is 𝑥𝑚𝑒𝑑𝑖𝑎𝑛xmedian = 𝑥(𝑛+12)x(n+12) where 𝑥(1),𝑥(2),...,𝑥(𝑛)x(1),x(2),...,x(n) are the elements sorted from the least to the greatest. Please note the difference in starting index when you work with indices in Python. A list with even number of elements should take the average of two numbers in the middle. 𝑥𝑚𝑒𝑑𝑖𝑎𝑛=𝑥(𝑛2)+𝑥(𝑛2+1)2xmedian=x(n2)+x(n2+1)2 This should be a full implementation of my_median. Hence, make sure that it works with lists with both odd and even number of elments. You may assume that there is at least one number in the list. (Optional for 1 extra credit point) In addition, if there are elements that are not comparable (e.g., complex number or None), ignore them and return the median of numbers only. In order to handle incomparable numbers, you may want to use a for loop to filter out numbers of int or float type and store in a new array. Start with this code: def my_median(inputList):
def my_median(inputList): cleanList = [ i for i in inputList if type(i)==int or type(i)==float] cleanList.sort() length = len(cleanList) if (len(cleanList)%2==0): median=(cleanList[int(length/2)-1]+cleanList[int(length/2)])/2 else: median = cleanList[int((length+1)/2)-1] return(median)
Create a list named `four_to_eighty` that contains numbers starting from 4, ending with 80, and increasing in multiples of 4. You may use range() function, but make sure that the type is `list`.
four_to_eighty = list(range(4,81,4))
Write a function named hex2dec() that takes a hexadecimal number as a string (e.g., 'FF01A5', 'fa3b05') and converts it to a decimal number as integer. One way of doing this would be : Create a dictionary called hexDict with letters "0" to "F" as keys and 0 to 15 as values. (already coded for you) Reverse the string and make it uppercase letters Initialize a variable (e.g., decNum) for a resulting decimal number to 0. Use a for loop with an index going from 0 to (length of the string)-1 (i.e., for index in range(len(hexStr)): ). Within the loop, keep adding the (ℎ𝑒𝑥𝑛𝑢𝑚𝑏𝑒𝑟)∗16(𝑖𝑛𝑑𝑒𝑥)(hexnumber)∗16(index) to the decimal number. Return the final decimal number If you are not sure about the logic watch the following video https://www.youtube.com/watch?v=pg-HEGBpCQk Copy & paste the following code to begin your solution: def hex2dec(hexString): # A dictionary to convert hexadecimal character to integer is provided below # \ can be used to contune your code to the next line, but it is not necessary in an IPython cell. hexdict = {'0':0, '1':1, '2':2, '3':3, '4':4, \ '5':5, '6':6, '7':7,'8':8, '9':9,\ 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15} # Complete the function. You may not need more than 5 lines.
def hex2dec(hexString): hexdict = {'0':0, '1':1, '2':2, '3':3, '4':4, \ '5':5, '6':6, '7':7,'8':8, '9':9,\ 'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15} hexString=hexString[::-1].upper() decNum=0 for i in range(len(hexString)): decNum+=hexdict[hexString[i]]*(16**i) return decNum
Generate an array of 15 random numbers from from 0 (inclusive) to 5 (exclusive) using numpy's random.randint() function. Assign it to a variable rand_array1. Hint: Look up the documentation to figure out how many and what arguments you need to pass to the randint() function. Generate another array of 15 random numbers from 5 (inclusive) to 10 (exclusive) and assign it to a variable rand_array2. Create a matrix (two-dimentional numpy array) of 5 rows and 3 columns using the first array and assign it to a variable named mat1. Create another matrix of 3 rows and 5 columns using the second array and assign it to a varaible named mat2. Calculate the sum of the products of the elements in the 3^{rd}3rd row of mat1 and the corresponding elements in the 4^{th}4th column of mat2. Note that the 3^{rd}3rd row should be extracted with mat1[2,:] instead of mat1[3,:] because index starts from 0 in Python. Similarly, you need to use mat2[:,3] to extract the 4^{th}4th column. Assign the calulated value to a variable named a34.
rand_array1 = np.random.randint(0,5,15) rand_array2 = np.random.randint(5,10,15) mat1 = rand_array1.reshape(5,3) mat2 = rand_array2.reshape(3,5) a34 = np.sum(mat1[2,:]*mat2[:,3])
Create a numpy array of 40 random numbers drawn from a normal distribution with a mean of \mu = 100μ=100 and a standard deviation \sigma = 10σ=10. And then, assign it to a variable random_sample. Hint: Use the numpy package's random.normal() function. From random_sample, create another numpy array (i.e., array with values True or False only). The value should be True if the corresponding number in random_sample is greater than or equal to the mean (i.e., 100). Assign the logical array to a variable is_ge_mean. From random_sample, create another numpy array where the values are less than the mean (i.e., 100). Assign it to a variable named low_sample.
random_sample = np.random.normal(100,10,40) is_ge_mean = random_sample >= 100 low_sample = random_sample[random_sample <100]
Question 8 (3pts): Compute the following statistics based on the given formula and store them in variables named sample_mean, sample_var, and sample_sd. Note that x_1, x_2,\ldots, x_Nx1,x2,...,xN are the 25 random numbers you have drawn from the normal distribution and N-1N−1 is used in the denominator for the calculation of sample variance. sample mean, \bar{x} = \frac{\sum_{i=1}^{N} x_i}{N}xˉ=N∑i=1Nxi sample variance, s^2 = \frac{1}{N-1}\sum_{i=1}^{N} (x_i-\bar{x})^2s2=N−11∑i=1N(xi−xˉ)2 sample standard deviation, s= \sqrt{s^2}s=s2 Compare the mean and standard deviation computed above with the mean and standard deviation of the original normal distribution. See how close these values are to those of the original distribution (i.e., population mean of 100 and population standard deviation of 10.) You may try increasing the sample size to a large number (e.g., 100,000 instead of 25) if they do not look similar to each other. But, do not include such coding in your submission.
sample_mean = random_sample.sum()/len(random_sample) sample_var = np.sum((random_sample - sample_mean)**2)/(len(random_sample)-1) sample_sd = np.sqrt(sample_var)