PY3

Area

Plot the area under a curve

#!/usr/bin/python3
from matplotlib import pyplot as plt
import numpy as np
x=np.arange(1,31)
y=x*x
plt.fill_between(x,y,color='blue', alpha=0.5)
plt.show()

Capitalize the entire first field of standard input with Python

#!/usr/bin/python3
import sys,re
for line in sys.stdin:
word=line.split()
word1=re.split("\s",line)[0]
word1=word1.upper()
print(str(word1)," ".join(word[1:]),end=" ")
print()

Cartesian

Calculate the rectangular celestial coordinates of stars from right ascension, declination, and distance (Alpha Centauri given in example):

#!/usr/bin/python3

import sys
import astropy as ap
from astropy import units as u
from astropy.coordinates import SkyCoord, get_constellation
coord=sys.argv[1:6]
dist=float(sys.argv[7])
co=” “.join(coord)
c=SkyCoord(co, unit=(u.hourangle,u.deg),distance=dist)
print(c.represent_as(‘cartesian’))

Constel

Get a constellation name from given celestial coordinates

#!/usr/bin/python3

import sys
from astropy import units as u
from astropy.coordinates import SkyCoord, get_constellation 
coord=sys.argv[1:]
co=" ".join(coord)
c=SkyCoord(co, unit=(u.hourangle,u.deg))
print(get_constellation(c,short_name=False))

Clipboard

Get data from clipboard

import pandas as pd
pd.read_clipboard()

Days between two dates

[m2,d2,y2] = b.split('/')    
y1 = int(y1)
m1 = int(m1)
d1 = int(d1)
y2 = int(y2)
m2 = int(m2)
d2 = int(d2)
t1=date(y1,m1,d1)
t2=date(y2,m2,d2)
print((t2-t1).days)

Derivatives

import sympy as sym
x=sym.Symbol('x')
f=sym.atan(x**2)
print(f.diff(x))

Egyptian fractions in Python 3

Express a rational number as the sum of unit fractions.


fsum

Avoiding loss of precision with multiple partial sums


History

Save Python history to file:

import readline
readline.write_history_file('pyhistory.txt')

List

List your files sorted by name, with file sizes

#!/usr/bin/python3
import os,sys
dir = str(sys.argv[1])
files = sorted(filter(lambda x: os.path.isfile(os.path.join(dir,x)),os.listdir(dir)))
sizes = [(file_name,os.stat(os.path.join(dir,file_name)).st_size)
for file_name in files]
for file_name, size in sizes:
print("{:>9}".format(size), file_name)

Logic truth tables in Python

from sympy.logic.boolalg import truth_table
from sympy.abc import x,y,z
table = truth_table((x ^ y) ^ z, [x, y, z])
for t in table:
print('{0} -> {1}'.format(*t))

Lorentz

Calculate the relativistic Lorentz factor (for hard science fiction writers):

#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
major_ticks = np.arange(0, 101, 5)
minor_ticks = np.arange(0, 101, 1)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(minor_ticks, minor=True)
ax.grid(which='minor', alpha=0.3)
ax.grid(which='major', alpha=0.8)
x = np.arange(0.7, 1, 0.001)
y = 1/(np.sqrt((1-x**2)))
plt.plot(x*100, y)
plt.title("Lorentz Factor")
plt.xlabel("Real velocity (percentage of c)")
plt.ylabel("Apparent velocity (multiple of c)")
plt.show()

 

Maze

Generate an ASCII maze with Python

Median

Returns the medians of the array; that is, half the columns have values that are greater than the median, and half the columns have values that are less than the median.

#!/usr/bin/python3
import pandas,sys
name = str(sys.argv[1])
elements = pandas.read_csv(name)
print (elements)
medians = elements.median()
print("Medians of each column:")
print (medians)

Minmax

Find mininum and maximum elements in a column of data

#!/usr/bin/python3
import numpy, sys
name = str(sys.argv[1])
file = open(name,"r")
data = file.read().splitlines()
elements = list(numpy.array(data, dtype='float'))
min = numpy.min(elements)
max = numpy.max(elements)
print(f"Min = {min}")
print(f"Max = {max}")

Pandas

Pi range

Calculate 500 digits of pi starting at the 99,501st digit, with #Python

from sympy import * str(N(pi,100000))[-500:]

Plot 3D

from sympy import symbols
from sympy.plotting import plot3d
x, y = symbols('x y')
plot3d(x**2+y**2, (x, -5, 5), (y, -5, 5))

 

 

Plot norm

Plot the normal distribution for a mean of zero and a standard deviation of one (blue) and two (red):

#!/usr/bin/python3 

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

x1 = np.arange(-3, 3, 0.001)
x2 = np.arange(-3, 3, 0.001)

plt.plot(x1, norm.pdf(x1, 0, 1))
plt.plot(x2, norm.pdf(x2, 0, 2), color='red', linewidth=3)
plt.show()

 

Plot Stats

Select mean, standard deviation and count and plot the spread

#!/usr/bin/python3

#USAGE: ./plotrand mean standard-deviation count

import sys,pylab,random
mean=float(sys.argv[1])
dev=float(sys.argv[2])
count=int(sys.argv[3])
x = [random.gauss(mean,dev) for i in range (count)]
y = [random.gauss(mean,dev) for i in range (count)]
pylab.plot(x,y,'bo')
pylab.savefig('points.png')

Primitive Pythagorean triples up to n

#!/usr/bin/python3

import sys,math
n = int(sys.argv[1])

print([(x,y,z) for x in range(1,n+1) for y in range(x,n+1,1) for z in range(y,n+1,1) if x**2 + y**2 == z**2 and math.gcd(x,y) == 1])


Pulse-width modulated square wave

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
t = np.linspace(0, 1, 500, endpoint=False)
plt.figure()
sig = np.sin(2 * np.pi * t)
pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
plt.subplot(2, 1, 1)
plt.plot(t, sig)
plt.subplot(2, 1, 2)
plt.plot(t, pwm)
plt.ylim(-1.5, 1.5)
plt.show()

Rational from decimal

Approximate pi from increasingly better fractions

#!/usr/bin/python3

from fractions import Fraction
import sys
import numpy as np
x = np.pi
d = 10
while d < 1000000000:
    f=x, Fraction.from_float(x).limit_denominator(d)
    a=f[1]
    b=str(a)
    c=eval(b)
    print ("Denom. limit=",d)
    print (a,"=",c)
    d = d * 10

Satan

Summon Satan

#!/usr/bin/python3
import turtle
from PIL import Image
turtle.bgcolor("green")
t=turtle.Turtle()
t.color("red","blue")
t.begin_fill()
for i in range(0,5):
t.forward(200)
t.right(144)
t.end_fill()
t.hideturtle()
canvas=turtle.getcanvas()
name="satan.ps"
canvas.postscript(file=name)
psimage=Image.open(name)
psimage.save("satan.png")

Scrape

Extract all the links from a web page:

#!/usr/bin/python3
import requests,sys
from bs4 import BeautifulSoup
url = sys.argv[1]
r = requests.get(url)
htmlContent = r.content
soup = BeautifulSoup(htmlContent, 'html.parser')

anchors = soup.find_all('a')
all_links = set()
for link in anchors:
if(link.get('href') != '#'):
linkText = url+str(link.get('href'))
all_links.add(link)
print(linkText)

sinc

Normalized (red) and unnormalized (blue) sinc function

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-np.pi*6,np.pi*6,1000)
y1=np.sinc(x)
y2=np.sinc(x/np.pi)
plt.plot(x,y1,color="blue")
plt.plot(x,y2,color="red")
plt.show()


 

SinCos

Display trig functions with Python

#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi,np.pi,100)
y = np.sin(x)
z = np.cos(x)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.plot(x,y, 'c', label='y=sin(x)')
plt.plot(x,z, 'm', label='y=cos(x)')
plt.legend(loc='upper left')
plt.show()

Spell out numbers with Python:

pip install inflect
import inflect
inflector=inflect.engine() print(inflector.number_to_words(8675309))

Vday

#!/usr/bin/python3
from matplotlib import pylab
import scipy
x = scipy.linspace(-2,2,1000)
y1 = scipy.sqrt(1-(abs(x)-1)**2)
y2 = -3*scipy.sqrt(1-(abs(x)/2)**0.5)
pylab.fill_between(x, y1, color='red')
pylab.fill_between(x, y2, color='red')
pylab.xlim([-2.5, 2.5])
pylab.text(0, -1.5, 'Klingons do\nNOT celebrate\nValentines\nDay', fontsize=24, fontweight='bold',
color='white', horizontalalignment='center')
pylab.savefig('heart.png')

 

Wrap

Reformat standard input to any width with Python


#!/usr/bin/python3
import sys
import textwrap
w=int(sys.argv[1])
for line in sys.stdin:
print(textwrap.fill(line,width=w))