Read More

**Mathematical Operations in Python**

```
print("***** QUESTION 1 *****\n");
def factorial(n):
"""
Recursively calculat the factorial of n
"""
# Base case
if n == 1:
return 1
return n*factorial(n-1)
def calnWk(n, k):
return n**k
def calnPk(n ,k):
return factorial(n)/factorial(n-k)
def calnCk(n, k):
return calnPk(n, k)/factorial(k)
print("\n***** QUESTION 2 *****\n");
# Use built-in functions to get the coefficient
from sympy import *
x, y = symbols('x y')
exp = (2*x**2-4*y**3)**30
coeff_real = exp.expand().coeff(x**20).coeff(y**60)
print("The coefficient calculated using built-in function for x^20*y^60 is " + str(coeff_real))
print("\n***** QUESTION 3 *****\n");
# Now get the coefficient using the functions from Part 1
# The coefficient of x^90 *y^10 can be calculated as a combination, selecting the element 90 from the 100 available elements
# Coefficients of x and y: (ax^c + by^d)^n
a = 2
b = -4
c = 2
d = 3
n = 30 #
k = 20 #
coeff_calc = calnCk(n,k)*a**(n-k) *b**k
print("The coefficient calculated using the functions from Part 1 for for x^20*y^60 is: " + str(coeff_calc))
"""
print("\n***** QUESTION 4 *****\n");
# Create a random 3x3 matrix
import numpy as np
A = np.random.uniform(low = 0, high = 1, size=(3,3)) # matrix of random integers from 1 to 10
b = np.matrix([[1],[0],[0]])
# Check if Ax = b has a solution
print("Matrix A is:\n" + str(A))
print("\nVector b is:\n" + str(b))
x = np.linalg.solve(A,b)
print("\nThe solution x for Ax = b is:\n" + str(x))
```

**Calculating jiffies and server latency**

```
import os
import time
import datetime
import logging
import pexpect
# Program configurations.
log_file = "latency.log"
server = "www.lfedge.org"
interval = 1
threshold = 250
# Change it to false to save only to log file.
print_stdout = True
logging.basicConfig(filename=log_file, level=logging.DEBUG, format='%(levelname)s:%(asctime)s:%(message)s')
log = logging.getLogger(__name__)
if __name__ == "__main__":
program_banner = f"Ping Interval: {interval}, Destination: {server} Threshold to Log (msec): {threshold}"
log.info(program_banner)
if print_stdout:
print(program_banner)
command = f"ping -i {interval} {server}"
child = pexpect.spawn(command)
child.timeout = 1200
first_line = True
while True:
line = child.readline()
if not line:
break
if line.startswith(b"ping: unknown host"):
if print_stdout: print("Unknown host: " + server)
log.info("Unknown host: " + server)
break
if first_line:
first_line = False
continue
ping_time = float(line[line.find(b"time=") + 5 : line.find(b" ms")])
line = time.strftime("%m/%d/%Y %H:%M:%S") + ": " + str(ping_time) + " ms"
if print_stdout: print(line)
if ping_time> threshold:
log.info(log_file, line + "\n")
```