Using Python to graph relativistic apparent speed as a starship approaches c
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8,6))
major_ticks = np.arange(0, 101, 5)
unit_ticks = np.arange(0, 101, 1)
minor_ticks = np.arange(0, 101, 0.2)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks)
ax.set_xticks(unit_ticks, minor=True)
ax.set_yticks(unit_ticks, minor=True)
ax.grid(which='major', color='gray', linestyle='-', linewidth=0.8, alpha=0.8)
ax.grid(which='minor', color='black', linestyle='-', linewidth=0.5, alpha=0.7)
x = np.arange(0.7, 0.999, 0.0001)
y = x / np.sqrt(1 - x**2)
plt.plot(x * 100, y, color='blue', linewidth=2)
ax.set_xlim(70, 100)
ax.set_ylim(0, max(y)*1.1)
plt.xlabel("Real speed (percentage of c)")
plt.ylabel("Apparent speed (multiple of c)")
plt.tight_layout()
plt.show()
Plot a cube.
#!/usr/bin/python3
import numpy as np
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import matplotlib.pyplot as plt
points = np.array([[-1, -1, -1],
[1, -1, -1 ],
[1, 1, -1],
[-1, 1, -1],
[-1, -1, 1],
[1, -1, 1 ],
[1, 1, 1],
[-1, 1, 1]])
Z = points
Z = 10.0*Z
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
r = [-1,1]
X, Y = np.meshgrid(r, r)
ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])
verts = [[Z[0],Z[1],Z[2],Z[3]],
[Z[4],Z[5],Z[6],Z[7]],
[Z[0],Z[1],Z[5],Z[4]],
[Z[2],Z[3],Z[7],Z[6]],
[Z[1],Z[2],Z[6],Z[5]],
[Z[4],Z[7],Z[3],Z[0]]]
ax.add_collection3d(Poly3DCollection(verts, facecolors='cyan', linewidths=1, edgecolors='r', alpha=.20))
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
Archimedes spiral with turtle graphics
#!/usr/bin/env python3
from turtle import *
from math import *
color("blue")
speed(0)
down()
for i in range(200):
t = i*pi/20
r = 1+5*t
goto(r*cos(t), r*sin(t))
done()
#!/usr/bin/env python3
from datetime import*
t=datetime.today()
print(“Only”,(datetime(t.year,12,25)-t).days,”shopping days until Christmas.”)
Rot13 with Python
#!/usr/bin/python3
import sys, string
def rot13(s):
return ''.join([chr(x.islower() and ((ord(x) - 84) % 26) + 97
or x.isupper() and ((ord(x) - 52) % 26) + 65
or ord(x))
for x in s])
for line in sys.stdin:
sys.stdout.write(rot13(line))
Plot the area under a curve with Python
#!/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()
Generating truth tables
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))
Boolean truth tables in Python
#!/usr/bin/env python3
import sys
from itertools import product
bexp=" ".join(sys.argv[1:])
code=compile(bexp,"<string>","eval")
names=code.co_names
print("\n" + " ".join(names),":",bexp)
for values in product(range(2), repeat=len(names)):
env=dict(zip(names,values))
print(" ".join(map(str,values)),":",int(eval(code,env)))
Plot a 3D sphere with Python
#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
theta, phi = np.linspace(0, 2 * np.pi, 50), np.linspace(0, np.pi, 20)
THETA, PHI = np.meshgrid(theta, phi)
R = 1.0
X = R * np.sin(PHI) * np.cos(THETA)
Y = R * np.sin(PHI) * np.sin(THETA)
Z = R * np.cos(PHI)
fig = plt.figure()
ax = fig.add_subplot(1,1,1, projection=’3d’)
plot = ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1, linewidth=.1, color=’red’, antialiased=False, alpha=1)
plt.show()
Print the shortest and longest verses in the Bible with Python
#!/usr/bin/env python3
import os
base=os.path.dirname(os.path.abspath(__file__))
path=os.path.join(base,"kjv.txt")
with open(path) as f:
print("Shortest verse:",min(f,key=len))
with open(path) as f:
print("Longest verse:",max(f,key=len))
#!/usr/bin/env python3 import matplotlib.pyplot as p,numpy as n x,y=n.meshgrid(n.linspace(-4,4,512),n.linspace(-4,4,512)) z=(1-x/2+x**4+y**3)*n.exp(-x**2-y**2)*(1-x/3-y**4)*(3-y+x**2) z+=.5*n.sin(.8*x+.6*y)+.4*n.cos(.5*x-.7*y)+.3*n.sin(.6*x-.4*y) p.contour(x,y,z,levels=n.linspace(z.min(),z.max(),25),cmap='terrain') p.show()
Top 20 bash commands in Python
#!/usr/bin/env python3
from collections import Counter
import matplotlib.pyplot as plt
import os
history_file = os.path.expanduser("~/.bash_history")
counter = Counter()
with open(history_file, "r", errors="ignore") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
cmdline = line.split("|", 1)[0].strip()
parts = cmdline.split()
if not parts:
continue
cmd = parts[1] if parts[0] == "sudo" and len(parts) > 1 else parts[0]
counter[cmd] += 1
top = counter.most_common(20)
commands, counts = zip(*top)
commands = commands[::-1]
counts = counts[::-1]
plt.figure(figsize=(10, 6))
plt.barh(commands, counts)
plt.title("Top 20 Bash Commands (frequency)")
plt.xlabel("Usage count")
plt.tight_layout()
plt.show()
List bash commands by frequency
#!/usr/bin/env python3
import os
history_file = os.path.expanduser("~/.bash_history")
counts = {}
with open(history_file, "r", errors="ignore") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
cmdline = line.split("|", 1)[0].strip()
parts = cmdline.split()
if not parts:
continue
cmd = parts[1] if parts[0] == "sudo" and len(parts) > 1 else parts[0]
counts[cmd] = counts.get(cmd, 0) + 1
sorted_cmds = sorted(counts.items(), key=lambda x: x[1], reverse=True)
for cmd, n in sorted_cmds:
print(f"{n} {cmd:20}")
Put text in an ASCII art box:
#!/usr/bin/env python3
import sys
print(“+” + “-” * 62 + “+”)
for line in sys.stdin:
print(f”| {line.rstrip():<60} |”)
print(“+” + “-” * 62 + “+”)
Reformat standard input to any width
#!/usr/bin/python3
import sys
import textwrap
w=int(sys.argv[1])
for line in sys.stdin:
print(textwrap.fill(line,width=w))
refive
Take scattershot wikimedia table data and line it up nicely, five columns per row, with Python
#!/usr/bin/env python3
import sys
count = 0
for line in sys.stdin:
line = line.rstrip()
if line == "|-":
continue
if line.startswith("|[["):
print(line)
count += 1
if countย % 5 == 0:
print("|-")
else:
if line.startswith("{|"):
count = 0
print(line)
Use Python to reverse stdin by words (rev will do this by characters)
#!/usr/bin/env python3
import sys
for line in sys.stdin:
print(' '.join(line.split()[::-1]))
Convert text to italics with Python
#!/usr/bin/env python3
import sys
a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
b="๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐ป"
print(" ".join(sys.argv[1:]).translate(str.maketrans(a,b)))
#!/usr/bin/env python3
import sys
c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
b="๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐ป๐ผ๐ฝ๐พ๐ฟ๐๐๐๐๐๐
๐๐๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต"
print("".join(b[c.find(x)] if x in c else x for x in " ".join(sys.argv[1:])))
Calculate parallel resistance (or series capacitance) with Python
#!/usr/bin/env python3 import sys,numpy as n print(sys.argv[1:],'->',1/(1/n.array(sys.argv[1:],float)).sum())
Python replacement for the uniq command.
#!/usr/bin/env python3
import sys
seen = set()
for line in sys.stdin:
if line not in seen:
seen.add(line)
sys.stdout.write(line)
This is not equivalent to sort -u because it preserves the original order, and it’s not equivalent to uniq because it removes duplicates even when they’re not adjacent.
#!/usr/bin/env python3
import sys
n = int(sys.argv[1])
ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
teens = ["ten", "eleven", "twelve", "thirteen", "fourteen","fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
tens = ["", "", "twenty", "thirty", "forty","fifty", "sixty", "seventy", "eighty", "ninety"]
if n < 10:
print(ones[n])
elif n < 20:
print(teens[n - 10])
else:
t = n // 10
o = nย % 10
if o == 0:
print(tens[t])
else:
print(f"{tens[t]}-{ones[o]}")
#!/usr/bin/python3
from random import shuffle, randrange
def makemaze(w=20,h=12):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
ver = [["| "] * w + ['|'] for _ in range(h)] + [[]]
hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
shuffle(d)
for (xx, yy) in d:
if vis[yy][xx]: continue
if xx == x: hor[max(y, yy)][x] = "+ "
if yy == y: ver[y][max(x, xx)] = " "
walk(xx, yy)
walk(randrange(w), randrange(h))
s = ""
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
print(makemaze())
Strip punctuation from stdin
#!/usr/bin/env python3
import sys
for line in sys.stdin:
sys.stdout.write(
.join(c for c in line if c.isalnum() or c.isspace())
)
Find anagrams with Python
#!/usr/bin/env python3
from collections import Counter
import sys,os
s=sys.argv[1]
def anagrams(word,words):
cw=Counter(word)
return [w for w in words if Counter(w)==cw]
base=os.path.dirname(os.path.abspath(__file__))
path=os.path.join(base,"words.txt")
with open(path) as f:
lines=f.read().splitlines()
print(anagrams(s,lines))
Convert csv data to sc format
#!/usr/bin/env python3
import sys,string
d=','
a="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
r=0
o=[":"]
for l in open(sys.argv[1]):
c=0
for p in l.rstrip().split(d):
if not p:continue
try:
o+=["let %s%d = %d"%(a[c],r,int(p))]
except:
o+=["leftstring %s%d = %s"%(a[c],r,p if p[0]=='"' else '"%s"'%p)]
c+=1
r+=1
print("\n".join(o))


















