Python Code Examples

This is a PY2 file that creates user entered Polynomials and randomly generated polynomials.

import random

def make_2nd_degree_poly(k2, k1, k0): return lambda x:((“p(x) = “+ str(k2) +”x^2 + ” + str(k1) + “x + ” +str(k0)) , k2*(x**2) + k1*(x) +k0, “at x=” + str(x))

def make_2nd_deg_polys(coeffs):
polyList = []
for i in range (0,len(coeffs)):
polyList.append(make_2nd_degree_poly(coeffs[i][0],coeffs[i][1],coeffs[i][2]))
return polyList

def map_polys(polys,numbers):
poly_map_list=[]
for i in range(numbers+1):
for n in range(0,len(polys)):
poly_map_list.append(polys[n](i))

return poly_map_list

def display_poly_maps(poly_maps):
for i in range(len(poly_maps)):
rslt = poly_maps[i]
print ‘p(x)= %s = %s, %s’ % (rslt[0], str(rslt[1]), rslt[2])

def poly_dance(coeffs,xvals):
polys=make_2nd_deg_polys(coeffs)
poly_maps = map_polys(polys,xvals)
return poly_maps

def gen_rand_coeff(a, b):
sign = random.randint(1, 1000)
if sign < 500:
return -random.randint(a, b)
else:
return random.randint(a, b)

def calculate_nth_poly(coeffs, x,n):
solution = 0
for i in range (n+1):
solution = solution + coeffs[n-i]*(x**(n-i))
return solution

def make_nth_deg_rand_poly(n, a, b):
coeff_list = []
toop_part1 = “”
for i in range(n):
coeff_list.insert(0,gen_rand_coeff(a, b))
toop_part1 = toop_part1 + str(coeff_list[0]) + “x^” + str(n-i) + ” + ”
coeff_list.insert(0,gen_rand_coeff(a, b))
toop_part1 = toop_part1 + str(coeff_list[0])

return lambda x: (toop_part1,calculate_nth_poly(coeff_list,x,n), “at x=” + str(x))
def make_nth_deg_rand_polys(num_polys,n,a,b): return[make_nth_deg_rand_poly(n, a, b) for i in range(num_polys)]

def rand_poly_dance(num_polys, n, a, b, xval):
polys = make_nth_deg_rand_polys(num_polys, n, a, b)
poly_maps = map_polys(polys, xval)
return poly_maps

def sorted_rand_poly_dance(num_polys, n, a, b, xval):
base_list = rand_poly_dance(num_polys, n, a, b, xval)
return sorted(base_list, key=lambda x:x[1], reverse= True)


This is an example of using regular expressions to parse NASA data logs, sort it into groups, and output specific data:

#!/usr/bin/python

##Extracts the IP address and Bytes transferred and outputs to terminal

import sys, re

for n in [str(x) for x in sys.stdin.readlines()]:
#IP
match1 = re.search(r'(\d+\.\d+\.\d+\.\d+|\w+\.com|\w+\.edu|\w+\.net|\w+\.edu)’,n)
#Bytes
match2 = re.search(r’\s\d\d*\s(\d\d*)’,n)
if match1 and match2:
sys.stdout.write(str(match1.group(1))+’ ‘+str(match2.group(1)+’\n’))

 

css.php