^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^BOOLEAN^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # true and true --> true # false and true --> false # true and false --> false # false and false --> false if isRaining and isSunny: print("We might see a rainbow") # OR # true and true --> true # false and true --> true # true and false --> true # false and false --> false if isRaining or isSunny: print("It might be rainy or it might be sunny") # NOT # true --> false # false --> true if not isRaining: print("It must be raining") ages = [12, 18, 39, 87, 7, 2] for age in ages: isAdult = age > 17; if not isAdult: print("Being " + str(age) + " does not make you an adult.") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^LIST, SORT AND TUBLES^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # Least to Greatest pointsInaGame = [0, -10, 15, -2, 1, 12] sortedGame = sorted(pointsInaGame) print(sortedGame) # Alphabetically children = ["Sue", "Jerry", "Linda"] print(sorted(children)) print(sorted(["Sue", "jerry", "linda"])) # Key Parameters print(sorted("My favorite child is Linda".split(), key=str.upper)) print(sorted(pointsInaGame, reverse=True)) #Reverse sorting leaderBoard = {231: "CKL", 123:"ABC", 432:"JKC"} print(sorted(leaderBoard, reverse=True)) print(leaderBoard.get(432)) #Sort due to one of objects students = [ ('alice', 'B', 12), ('eliza', 'A', 16), ('tae', 'C', 15)] print(sorted(students, key=lambda student:student[0])) print(sorted(students, key=lambda student:student[1])) print(sorted(students, key=lambda student:student[2])) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Math Module Part I^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import math # Constants print(math.pi) print(math.e) print(math.nan) print(math.inf) print(-math.inf) # Trigonometry obst_direction = math.cos(math.pi / 4) print(obst_direction) print(math.sin(math.pi / 4)) # Ceiling and Floor cookies = 10.3 candy = 7 print(math.ceil(cookies)) print(math.ceil(candy)) age = 47.9 otherAge = 47 print(math.floor(age)) print(math.floor(otherAge)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Math Module Part 2^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import math # Factorial & Square Root print(math.factorial(3)) print(math.sqrt(64)) # Greatest Common Denominator GCD print(math.gcd(52, 8)) print(math.gcd(8, 52)) print(8/52) print(2/13) # Degrees and Radians print(math.radians(360)) print(math.pi * 2) print(math.degrees(math.pi * 2)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Random Module^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import random # Random Numbers print(random.random()) decider = random.randrange(2) if decider == 0: print("HEADS") else: print("TAILS") print(decider) print("You rolled a " + str(random.randrange(1, 7))) # Random Choices lotteryWinners = random.sample(range(100), 5) print(lotteryWinners) possiblePets = ["cat", "dog", "fish"] print(random.choice(possiblePets)) cards = ["Jack", "Queen", "King", "Ace"] random.shuffle(cards) print(cards) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Statistics Module^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import statistics import math agesData = [10, 13, 14, 12, 11, 10, 11, 10, 15] print(statistics.mean(agesData)) print(statistics.mode(agesData)) print(statistics.median(agesData)) print(sorted(agesData)) print(statistics.variance(agesData)) print(statistics.stdev(agesData)) print(math.sqrt(statistics.variance(agesData))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Itertools Part 1^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import itertools # Infinite Counting for x in itertools.count(50, 5): print(x) if x == 80: break; x = 0; # Infinite Cycling for c in itertools.cycle([1, 2, 3, 4]): print(c) x = x + 1 if x > 50: break; # Infinite Repeating for r in itertools.repeat(True): print(r) x = x + 1 if x > 100: break; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Itertools Part 2^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import itertools # Permutations: Order matters - some copies with same inputs but in different order election = {1: "Barb", 2:"Karen", 3:"Erin"} for p in itertools.permutations(election): print(p) for p1 in itertools.permutations(election.values()): print(p1) # Combinations: Order does not matter - no copies with same inputs colorsForPainting = ["Red", "Blue", "Purple", "Orange", "Yellow", "Pink"] for c in itertools.combinations(colorsForPainting, 3): print(c) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Tempfile Module^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import tempfile # Create a temporary file tempFile = tempfile.TemporaryFile() # Write to a temporary file tempFile.write(b"Save this special number for me: 5678309") tempFile.seek(0) # Read the temporary file print(tempFile.read()) # Close the temporary file tempFile.close() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Zipfile Module^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import zipfile # Open and List zip = zipfile.ZipFile('Archive.zip', 'r') print(zip.namelist()) # Metadata in the zip folder for meta in zip.infolist(): print(meta) info = zip.getinfo("purchased.txt") print(info) # Access to files in zip folder print(zip.read("wishlist.txt")) with zip.open('wishlist.txt') as f: print(f.read()) # Extracting files #zip.extract("purchased.txt") zip.extractall() # Closing the zip zip.close() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Datetime Module Part I^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ from datetime import datetime now = datetime.now() print(now.date()) print(now.year) print(now.month) print(now.hour) print(now.minute) print(now.second) print(now.time()) # Getting more control over formatting from datetime import datetime now = datetime.now() print(now.strftime("%a %A %d")) print(now.strftime("%b %B %m")) print(now.strftime("%A %B %d")) print(now.strftime("%H : %M : %S %p")) print(now.strftime("%y %Y")) # Calendar Module from datetime import datetime, timedelta import calendar now = datetime.now() testDate = now + timedelta(days=2) myFirstLinkedInCourse = now - timedelta(weeks=3) print(testDate.date()) print(myFirstLinkedInCourse.date()) if testDate > myFirstLinkedInCourse: print("Comparison works") cal = calendar.month(2001, 10) print(cal) cal2 = calendar.weekday(2001, 10, 11) print(cal2) print(calendar.isleap(1999)) print(calendar.isleap(2000)) # Create a Timer with the Time module import time run = input("Start? >") seconds = 0 if run == "yes": while seconds != 10: print(">", seconds) time.sleep(1) seconds += 1 print(">", seconds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^HTML Parser Module^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ from html.parser import HTMLParser class HTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Start tag: ", tag) for attr in attrs: print("attr:", attr) def handle_endtag(self, tag): print("End tag: ", tag) def handle_comment(self, data): print("Comment: ", data) def handle_data(self, data): print("Data: ", data) parser = HTMLParser() parser.feed("Coder

I am a coder

") print() input = input("Put in HTML Code") parser.feed(input) print() htmlFile = open("sampleHTML.html", "r") s = "" for line in htmlFile: s += line parser.feed(s) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Text Wrap Module^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ import textwrap websiteText = """ Learning can happen anywhere with our apps on your computer, mobile device, and TV, featuring enhanced navigation and faster streaming for anytime learning. Limitless learning, limitless possibilities.""" print("No Dedent:") print(textwrap.fill(websiteText)) print("Dedent") dedent_text = textwrap.dedent(websiteText).strip() print(dedent_text) print("Fill") print() print(textwrap.fill(dedent_text, width=50)) print(textwrap.fill(dedent_text, width=100)) print("Controlling Indent") print(textwrap.fill(dedent_text, initial_indent=" ", subsequent_indent=" ")) print("Shortening Text") short = textwrap.shorten("LinkedIn.com is great!", width=15, placeholder="...") print(short) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^HTTP Package^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # https://www.googleapis.com/books/v1/volumes?q=isbn:1101904224 import urllib.request import json import textwrap with urllib.request.urlopen("https://www.googleapis.com/books/v1/volumes?q=isbn:1101904224") as f: text = f.read() decodedtext = text.decode('utf-8') print(textwrap.fill(decodedtext, width=50)) print() obj = json.loads(decodedtext) print(obj['kind']) print(obj['items'][0]['searchInfo']['textSnippet']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^PYTHON TURTLE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #Turtle is used to create graphic through python and results of calculations. --#To generate a line import turtle wn = turtle.Screen() elsa = turtle.Turtle() elsa.forward(100) wn.exitonclick() --#To generate a square import turtle wn = turtle.Screen() elsa = turtle.Turtle() elsa.forward(100) for i in range(4): elsa.forward(100) #lenght of line elsa.right(90) #angle and ratio #elsa.right(random.uniform(-40,10)) #elsa.forward(random.uniform(-5,5)) wn.exitonclick() --#To generate colored line and background import turtle wn = turtle.Screen() elsa = turtle.Turtle() elsa.color("cyan") #color of line wn.bgcolor("blue") #color of background for i in range(4): elsa.forward(100) elsa.right(90) wn.exitonclick() --#To create a spriral pattern import turtle wn = turtle.Screen() elsa = turtle.Turtle() elsa.color("cyan") #color of line wn.bgcolor("blue") #color of background for i in range(10): for i in range(2): elsa.forward(100) elsa.right(60) elsa.forward(100) elsa.right(120) elsa.right(36) wn.exitonclick() --#To create a star import turtle wn = turtle.Screen() elsa = turtle.Turtle() elsa.color("red") #color of line wn.bgcolor("orange") #color of background for i in range(10): elsa.forward(100) elsa.right(60) elsa.forward(100) elsa.right(120) elsa.right(36) wn.exitonclick() --#Turtle Pattern, Color, Speed import turtle wn = turtle.Screen() tommy = turtle.Turtle() tommy.shape("turtle") tommy.speed(40) tommy.color("red") a,b=0,1 while b<500: a,b=b,a+b print(b) for i in range(2): tommy.forward(b) tommy.right(100) wn.exitonclick() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^MATPLOTLIB^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --#general commands related to plot import matplotlib.pyplot as plt plt.plot([1,3.5,4,3,7]) plt.plot([1,2.5,9,14]) plt.xlabel('some numbers') plt.ylabel('some') plt.show() --#generate bullet points for each data import matplotlib.pyplot as plt plt.plot([1,2,3,4], [1,4,9,16], 'ro') plt.axis([0, 6, 0, 20]) #[xmin, xmax, ymin, ymax] plt.show() --#To generate sequence, numpy and matplotlib are used concurrently import numpy as np import matplotlib.pyplot as plt # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') #plt.plot(x,y,type) plt.show() --#generate two different graph with function import numpy as np import matplotlib.pyplot as plt def f(t): return np.exp(-t) * np.cos(4*np.pi*t) t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) plt.figure(1) plt.subplot(211) plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') plt.subplot(212) plt.plot(t2, np.cos(2*np.pi*t2), 'r--', label='amma') plt.legend(loc='best') plt.show() --#plot, subplot and figure commands import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) # a second figure plt.plot([4, 5, 6]) # creates a subplot(111) by default plt.figure(1) # figure 1 current; subplot(212) still current plt.subplot(211) # make subplot(211) in figure1 current plt.title('Easy as 1, 2, 3') # subplot 211 title #If you are making lots of figures, you need to be aware of one more thing: the memory required for a figure is not completely released until the figure is explicitly closed with close(). Deleting all references to the figure, and/or using the window manager to kill the window in which the figure appears on the screen, is not enough, because pyplot maintains internal references until close() is called. --#Title, axis and text inside graph import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') #generate text inside graph plt.axis([40, 160, 0, 0.03]) plt.grid(True) #generate grid true or false plt.show() --#linear,log,logsim,logit grapg visualization import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter # useful for `logit` scale # Fixing random state for reproducibility np.random.seed(19680801) # make up some data in the interval ]0, 1[ y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) # plot with various axes scales plt.figure(1) # linear plt.subplot(221) plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True) # log plt.subplot(222) plt.plot(x, y) plt.yscale('log') plt.title('log') plt.grid(True) # symmetric log plt.subplot(223) plt.plot(x, y - y.mean()) plt.yscale('symlog', linthreshy=0.01) plt.title('symlog') plt.grid(True) # logit plt.subplot(224) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) # Format the minor tick labels of the y-axis into empty strings with # `NullFormatter`, to avoid cumbering the axis with too many labels. plt.gca().yaxis.set_minor_formatter(NullFormatter()) # Adjust the subplot layout, because the logit one may take more space # than usual, due to y-tick labels like "1 - 10^{-3}" plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25, wspace=0.35) plt.show() --#Plotting over image can be realized with matplotlib. There is an official tutotial about it. --#Subplots are generated within several command in a single frame --#Generate graph in a function import matplotlib.pyplot as plt plt.rcParams['savefig.facecolor'] = "0.8" def example_plot(ax, fontsize=12): ax.plot([1, 2]) ax.locator_params(nbins=3) ax.set_xlabel('x-label', fontsize=fontsize) ax.set_ylabel('y-label', fontsize=fontsize) ax.set_title('Title', fontsize=fontsize) plt.close('all') #close the graph because those are kept in memory till the closing fig, ax = plt.subplots() example_plot(ax, fontsize=24) plt.tight_layout() --#plt.tight_layout() is used to adjust subplots plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0) --#Artists module is used to generate detailed figures. Official tutorial can be found online. --#Legend handle, official tutorial is available import matplotlib.lines as mlines import matplotlib.pyplot as plt blue_line = mlines.Line2D([], [], color='blue', marker='*', markersize=15, label='Blue stars') plt.legend(handles=[blue_line]) plt.show() --#Path command is available that desired shape could be placed with several command, import Path. --#Example # Imports import numpy as np import matplotlib.pyplot as plt # Create a new figure of size 8x6 points, using 100 dots per inch plt.figure(figsize=(8,6), dpi=80) # Create a new subplot from a grid of 1x1 plt.subplot(111) X = np.linspace(-np.pi, np.pi, 256,endpoint=True) C,S = np.cos(X), np.sin(X) # Plot cosine using blue color with a continuous line of width 1 (pixels) plt.plot(X, C, color="blue", linewidth=2.0, linestyle="-", label='cosine') # Plot sine using green color with a continuous line of width 1 (pixels) plt.plot(X, S, color="green", linewidth=10.0, linestyle="-", label='sine') plt.legend(loc='upper left', frameon=False) # Set x limits plt.xlim(-4.0,4.0) # Set x ticks plt.xticks(np.linspace(-4,4,9,endpoint=True)) # Set y limits plt.ylim(-1.0,1.0) # Set y ticks plt.yticks(np.linspace(-1,1,5,endpoint=True)) # Save figure using 72 dots per inch # savefig("../figures/exercice_2.png",dpi=72) # Show result on screen plt.show() --#ColorBar image = np.random.rand(5, 5) plt.imshow(image, cmap=plt.cm.hot) plt.colorbar() --#Colorbar and Array import numpy as np import matplotlib.pyplot as plt x, y = np.arange(5), np.arange(15)[:, np.newaxis] distance = np.sqrt(x ** 5 + y**2) plt.pcolor(distance) plt.colorbar() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^NUMPY^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #The lib is used to generate numerical model and solveing method with arrays. #Why it is useful: Memory-efficient container that provides fast numerical operations. --#generate a matrix import numpy as np a = np.arange(15).reshape(3, 5) #generate 3x5 maxtix and put the number till 15. b=np.array([1,2,3,4,5], int) c=np.concatenate((a,b)) #merge two different martix into one. print(c) --#plot the matrix import numpy as np import matplotlib.pyplot as plt a = np.arange(10,30).reshape(4, 5) print(a) plt.plot(a) --#Generate an array manual import numpy as np a=np.array([1,5,4,6]) print(a) --#np.zeros( (3,4) ) --#np.ones( (2,3,4), dtype=np.int16 ) --#np.empty( (2,3) ) --#Generate array with number and range import numpy as np from numpy import pi a=np.linspace( 0, 2, 9 ) # 9 numbers from 0 to 2 print(a) x = np.linspace( 0, 2*pi, 100 ) # useful to evaluate function at lots of points f = np.sin(x) print(f) --#arange and reshape commands import numpy as np a = np.arange(6) # 1d array print(a) b = np.arange(12).reshape(4,3) # 2d array print(b) c = np.arange(24).reshape(2,3,4) # 3d array print(c) #If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners: print(np.arange(10000)) print(np.arange(10000).reshape(100,100)) #To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions. np.set_printoptions(threshold='nan') --#matrix product and basic commands import numpy as np a = np.array([3,4,5,6,7,7]) b = np.arange(6) e=a*b #elementwise product d=a.dot(b) #matrix product c=np.dot(a,b) #another matrix product print(a) print(b) print(c) t=a<5 print(t) --#random generate array import numpy as np a = np.ones((2,3), dtype=int) #define type of number inside array b = np.random.random((3,3)) a *= 3 print(a) print(b) --#functions and basic commands such as max and min or add import numpy as np a=np.array([2,4,6,7,1,9]) x=a.sum() #sum of all numbers y=a.min() z=a.max() print(x,y,z) B = np.arange(3) np.exp(B) #arbitrary selected function np.sqrt(B) #function C = np.array([2., -1., 4.]) print(np.add(B, C)) #sum each row --#generate matrix from function import numpy as np def f(x,y): return 20*x+y b = np.fromfunction(f,(5,5),dtype=int) print(b) --#plotting from function with numpy import numpy as np import matplotlib.pyplot as plt def f(x,y): return 20*x**2+y**2 b = np.fromfunction(f,(5,5),dtype=int) print(b) plt.plot(b) plt.xlabel("CCC") plt.autoscale --#matrix, element, iteration import numpy as np def f(x,y): return 10*x+y b = np.fromfunction(f,(5,4),dtype=int) for row in b: #writing each array with iteration print(row) for element in b.flat: #writing each element in matrix print(element) --# import numpy as np import matplotlib.pyplot as plt def f(x,y): return 10*x+y b = np.fromfunction(f,(5,4),dtype=int) for row in b: #writing each array with iteration print(row) plt.plot(b) plt.plot(b*2) plt.plot(b**2) plt.grid(True) --#Shape Manupulating import numpy as np import matplotlib.pyplot as plt a = np.floor(10*np.random.random((3,4))) print(a) print(a.shape) print(a.ravel()) # returns the array, flattened print(a.reshape(6,2)) # returns the array with a modified shape print(a.T) # returns the array, transposed #If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated: b= np.floor(10*np.random.random((3,4))) print(b) print(b.reshape(3,-1)) print(np.vstack((a,b))) #stack two different matrix in a same pile vertically print(np.hstack((a,b))) #horizontally #The function column_stack stacks 1D arrays as columns into a 2D array. np.hsplit(a,4) # Split a into 3 --#Copy and paste, view studies import numpy as np a = np.arange(12).reshape(2,6) b = a # no new object is created b is a # a and b are two names for the same ndarray object print(a) print(b) d = np.arange(30).reshape(5,6) c = d.view() #The view method creates a new array object that looks at the same data. c is d c.base is d # c is a view of the data owned by a c.shape = 3,10 # a's shape doesn't change d.shape print(d) print(c) e = d.copy() #copy all element inside matrix barring id print(e) print(c is d) print(id(c) is id(d)) --#example wit picture import numpy as np import matplotlib.pyplot as plt def mandelbrot( h,w, maxit=20 ): """Returns an image of the Mandelbrot fractal of size (h,w).""" y,x = np.ogrid[ -1.4:1.4:h*1j, -2:0.8:w*1j ] c = x+y*1j z = c divtime = maxit + np.zeros(z.shape, dtype=int) for i in range(maxit): z = z**2 + c diverge = z*np.conj(z) > 2**2 # who is diverging div_now = diverge & (divtime==maxit) # who is diverging now divtime[div_now] = i # note when z[diverge] = 2 # avoid diverging too much return divtime plt.imshow(mandelbrot(400,400)) plt.show() --#Example arrays import numpy as np a=np.array([[1,4,5,6,7],[5,4,3,7,8]]) print(a) print("--------------") b=np.arange(12).reshape(3,4) print(b) print("--------------") c=np.floor(55*np.random.random((4,5))) print(c) print(c>44) --#random import numpy as np #a=np.random.seed(56) #b=np.random.rand(5) #c=np.random.rand(2,3) #d=np.random.rand(6).reshape((2,3)) #e=np.random.randint(5, 10) #f=np.random.random() #g=np.random.normal(1.5, 4.0) print(g) --#Random number import numpy as np import matplotlib.pyplot as plt for i in range(0,5): a=np.random.rand(11) plt.figure(1) plt.plot(a) plt.xlim(0,10) b=np.array([1,5,6,45,8]) plt.figure(2) plt.plot(b) --#Numpy Polynominals import numpy as np p = np.poly1d([3, 2, 5]) print(p(1)) print(p.roots) print(p.order) --#Numpy Polynominals import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 1, 20) y = np.cos(x) + 0.3*np.random.rand(20) p = np.poly1d(np.polyfit(x, y, 3)) t = np.linspace(0, 1, 200) plt.plot(x, y, 'o', t, p(t), '-') --#Numpy Polynominals import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 2, 20) y = np.cos(x) + 0.3*np.random.rand(20) plt.plot(x, y, 'o') --#Numpy Polynominals ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^SCIPY^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --#scipy.linalg (Linear Algebra module of scipy that enables various implimentation) import numpy as np from scipy import linalg arr = np.array([[1, 2],[3, 4]]) print(linalg.det(arr)) #determinant print(linalg.inv(arr)) #inverse arr = np.array([[3, 2], [6, 4]]) print(linalg.det(arr)) --#scipy.fftpack (FFT examination in python with scipy) import numpy as np from scipy import fftpack time_step = 0.02 period = 5. time_vec = np.arange(0, 20, time_step) sig = np.sin(2 * np.pi / period * time_vec) + 0.5 * np.random.randn(time_vec.size) sample_freq = fftpack.fftfreq(sig.size, d=time_step) sig_fft = fftpack.fft(sig) pidxs = np.where(sample_freq > 0) freqs = sample_freq[pidxs] power = np.abs(sig_fft)[pidxs] --#scipy.optimization module import numpy as np from scipy import optimize import matplotlib.pyplot as plt def f(x): return x**2 + 10*np.sin(x) x = np.arange(-10, 10, 0.1) plt.plot(x, f(x)) plt.show() print(optimize.fmin_bfgs(f, 0)) #min value print(optimize.fmin_bfgs(f, 3, disp=0)) #local min value print(optimize.basinhopping(f, 0)) #global min value print(optimize.fminbound(f, 0, 10)) #local min root = optimize.fsolve(f, 1) root2 = optimize.fsolve(f, -2.5) print(root) print(root2) --#stats and random numbers, scipy.stats --#interpolation: The scipy.interpolate is useful for fitting a function from experimental data and thus evaluating points where no measure exists. import numpy as np from scipy.interpolate import interp1d import matplotlib.pyplot as plt measured_time = np.linspace(0, 1, 10) noise = (np.random.random(10)*2 - 1) * 1e-1 measures = np.sin(2 * np.pi * measured_time) + noise linear_interp = interp1d(measured_time, measures) computed_time = np.linspace(0, 1, 50) linear_results = linear_interp(computed_time) cubic_interp = interp1d(measured_time, measures, kind='cubic') cubic_results = cubic_interp(computed_time) plt.plot(measures) plt.plot(linear_results) plt.plot(cubic_results) --#scipy.integrate for solving ODE and combine it with Fortran #scipy.integrate also features routines for integrating Ordinary Differential Equations (ODE). In particular, scipy.integrate.odeint() is a general-purpose integrator using LSODA (Livermore Solver for Ordinary Differential equations with Automatic method switching for stiff and non-stiff problems), see the ODEPACK Fortran library for more details. from scipy.integrate import odeint def calc_derivative(ypos, time, counter_arr): counter_arr += 1 return -2 * ypos counter = np.zeros((1,), dtype=np.uint16) time_vec = np.linspace(0, 4, 40) yvec, info = odeint(calc_derivative, 1, time_vec, args=(counter,), full_output=True) counter info['nfe'][:10] --#plotting damping and viscous force in scipy from scipy.integrate import odeint mass = 0.5 # kg kspring = 4 # N/m cviscous = 0.4 # N s/m eps = cviscous / (2 * mass * np.sqrt(kspring/mass)) nu_coef = cviscous / mass om_coef = kspring / mass def calc_deri(yvec, time, nuc, omc): return (yvec[1], -nuc * yvec[1] - omc * yvec[0]) time_vec = np.linspace(0, 10, 100) yarr = odeint(calc_deri, (1, 0), time_vec, args=(nu_coef, om_coef)) plt.plot(yarr) --#There is no Partial Differential Equations (PDE) solver in Scipy. Some Python packages for solving PDE’s are available, such as fipy or SfePy. --#scipy.signal import numpy as np import matplotlib.pyplot as plt from scipy import signal t = np.linspace(0, 5, 100) x = t + np.random.normal(size=100) plt.plot(t, x, linewidth=3) plt.plot(t, signal.detrend(x), linewidth=3) --#scipy.ndimage: The submodule dedicated to image processing in scipy is scipy.ndimage. --#A general example that predicts wind data of Copenhagen import numpy as np import matplotlib.pyplot as plt max_speeds = np.load('C:\\Users\\Solmaz\\Desktop\\max-speeds.npy') years_nb = max_speeds.shape[0] print(max_speeds) cprob = (np.arange(years_nb, dtype=np.float32) + 1)/(years_nb + 1) sorted_max_speeds = np.sort(max_speeds) print(cprob) print(sorted_max_speeds) from scipy.interpolate import UnivariateSpline quantile_func = UnivariateSpline(cprob, sorted_max_speeds) nprob = np.linspace(0, 1, 1e2) fitted_max_speeds = quantile_func(nprob) fifty_prob = 1. - 0.02 #So the stormwind speed occurring every 50 years can be guessed by: fifty_wind = quantile_func(fifty_prob) print(fifty_wind) plt.plot(fifty_wind, '*') plt.plot(fitted_max_speeds, '--') plt.plot(fifty_wind,'*') plt.plot(max_speeds,'--') --#Rather than knowing all functions in Numpy and Scipy, it is important to find rapidly information throughout the documentation and the available help. Here are some ways to get information: help np.v help np.vander