PY

 


Capone


Make the first field of standard input uppercase

#!/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()


Print a range of binary numbers in #Python

  • python -c “for i in range(0,32): print i, (format(i,’b’))”
#!/usr/bin/python

import sys 

a = int(sys.argv[1])
b = int(sys.argv[2])

for i in range (a, b+1):
    print(format (i, 'b'))

 


Find anagrams of a word in a list

#!/usr/bin/python
from collections import Counter
import sys
s=sys.argv[1]

def anagrams(word, words):
    result = []
    counter_word = Counter(word)
    for other_word in words:
        if Counter(other_word) == counter_word:
            result.append(other_word)
    return result

with open("words.txt") as wordfile:
    lines=wordfile.read().splitlines()
    print(anagrams(s,lines))

#!/usr/bin/python
from collections import Counter
def anagrams(word, words):
    result = []
    counter_word = Counter(word)
    for other_word in words:
        if Counter(other_word) == counter_word:
            result.append(other_word)
    return result

with open("words.txt") as wordfile:
    lines=wordfile.read().splitlines()
    for x in lines:
        ana=anagrams(x,lines)
        if len(ana) >1:
            print(str(ana))


 

Lotto

#!/usr/bin/python3

import random
random.seed()
items = [*range(1,50)]

for i in range (0,10):
    print (random.sample(items,6))


Plot the Lorentz factor against velocity

#!/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()

Pairpal


Find pairs of words which form palindromes and write to standard output

#!/usr/bin/python
import sys
file = open("words.txt","r")
words = file.read()
data = words.split("\n")
for y in data:
    for x in data:
        z = "".join([y,x])
        w = z[:][::-1]
        if w == z:
            v = "".join([y," ",x])    
            sys.stdout.write('\n'+v)

Plot some nearby stars

#!/usr/bin/python3
import matplotlib.pyplot as plt

types = ['Sol', 'A Centauri', 'Epsilon Eridani', '61 Cygni', 'Procyon', 'Epsilon Indi', 'Tau Ceti', '40 Eridani']
x_coords = [0,-1.6,6.2,6.4,-4.8,5.7,10.3,7.2]
y_coords = [0,-1.4,8.2,-6.1,10.3,-3.2,5.0,14.6]

for i,type in enumerate(types):
    x = x_coords[i]
    y = y_coords[i]
    plt.scatter(x, y, marker='x', color='red')
    plt.text(x+0.3, y+0.3, type, fontsize=9)
plt.show()


 


Convert float to fractions

#!/usr/bin/python3

from fractions import Fraction
import sys 
d = float(sys.argv[1])
f=d, Fraction.from_float(d).limit_denominator(1000)
a=f[1]
b=str(a)
c=eval(b)
print ("Decimal=",d)
print ("Fraction:",a,"=",c)
print ("Error=",c-d)


Abundant, deficient, and perfect numbers

#!/usr/bin/python3
import sys
beg=int(sys.argv[1])
end=int(sys.argv[2])
tt = []
for n in range(beg, end+1):
       for x in range(1,1+n//2):
               if n%x == 0:
                       tt.append(x)
       if sum(tt) == n:
               print(str(n) + " is perfect")
       elif sum(tt) > n:
               print(str(n) + " is abundant")
       elif sum(tt) < n:
               print(str(n) + " is deficient")
       tt = []



Euler’s constant:

#!/usr/bin/python3
import math
import numpy as np
e0 = 0
e = 2
n = 0
fact = 1
while(e-e0>np.nextafter(0,1)):
    e0=e
    n+=1
    fact*=2*n*(2*n+1)
    e+=(2.*n+2)/fact
    print(e),
print ("Computed e = "+str(e))
print ("Real e = "+str(math.e))
print ("Error = "+str(math.e-e))


Convert Arabic numerals to Roman

#!/usr/bin/python3

import sys
x=int(sys.argv[1])
anums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
rnums = "M CM D CD C XC L XL X IX V IV I".split()
ret = []
for a,r in zip(anums, rnums):
    n,x = divmod(x,a)
    ret.append(r*n)
print (.join(ret))


maze

#!/usr/bin/python3
from random import shuffle, randrange
def make_maze(w = 20, h = 10):
    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
if __name__ == '__main__':
    print(make_maze())


Fourier analysis

#!/usr/bin/python3

import numpy as np
import matplotlib.pyplot as plot
t=np.arange(0, 6.28, .01);
a=np.rint(np.sin(t))
plot.subplot(211)
plot.plot(t,a,'bo')
plot.xlabel('Time')
plot.ylabel('Amplitude')
plot.subplot(212)
plot.magnitude_spectrum(a,Fs=4)
plot.show()

fibonacci

fibseq=[1,1,]
fiblen=40
for x in range(1,fiblen-1):
        xcount=fibseq[x-1]+fibseq[x]
        fibseq.append(xcount)
        print(xcount)

Plot a set of data points in #Python

#!/usr/bin/python3

x = [60,65,47,88,62,12,32,72,38,100,87,99,35,93,58]
y = [40,41,45,11,63,67,83,30,57,23,3,96,25,48,54]

import pylab
pylab.plot(x,y,'bo')
pylab.savefig('xypoints.png')

Print a calendar


Plot the sinc function

#!/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt
in_array=np.linspace(-np.pi,np.pi,100)
out_array=np.sinc(in_array)
plt.plot(in_array,out_array,color="blue", marker="o")
plt.title("Sinc function")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()


Calculate days until Christmas

#!/usr/bin/python3
import datetime
today=datetime.date.today()
xmas=datetime.date(2022,12,25)
diff=xmas-today
d=diff.days
print ("Only",d,"shopping days until Christmas.")

 

Return all primes over an interval:

#!/usr/bin/python3

import sys

m=int(sys.argv[1])
n=int(sys.argv[2])

primes = [i for i in range(m,n) if all(i%j !=0 for j in range(2,int(i**0.5) + 1))]

print(primes)

Use list comprehension to make a #Python one-liner that prints the prime numbers from 1 to 5000:

python -c “print([i for i in range(1,5000) if all(i%j !=0 for j in range(2,int(i**0.5) + 1))])”


Plot a function in three dimensions

#!/usr/bin/python3
from sympy import symbols,cos,sin
z = symbols('z')
from sympy.plotting import plot3d_parametric_line
plot3d_parametric_line(cos(z)*sin(z/20),sin(z)*sin(z/20),z,(z,-31.41,31.41))

 

Max, min, mean, and standard deviation

 

#!/usr/bin/python3

import numpy
file = open("sample.txt","r")
data = file.read().splitlines()
elements = list(numpy.array(data, dtype = 'float'))
max = max(elements)
min = min(elements)
mean = round((numpy.mean(elements)),5)
std = round(numpy.std(elements),5)

print(f"Max = {max}")
print(f"Min = {min}")
print(f"Mean = {mean}")
print(f"Standard Deviation = {std}")

ABSMAG

Calculate absolute magnitude from stellar apparent visual magnitude and radial distance (LY)

#!/usr/bin/python

import math
import sys 

Mvis = float(sys.argv[1])
Dist = float(sys.argv[2])

Vabs = Mvis - 5 * (math.log10(Dist /  3.2616) -1)

print round(Vabs,3)

AVERAGE

Return the arithmetic mean of the arguments:

Excel:

Python:

data =[3546,3027,22,99,3208,348,77,1398,8567,2866,99,66,4272,2784,4429,88,3286,86,55,1766]
from numpy import mean
elements = [float(elements) for elements in data]
print (mean(elements))

PYPRIME

 

In Python return all primes over an interval:

#!/usr/bin/python3

import sys

m=int(sys.argv[1])
n=int(sys.argv[2])

primes = [i for i in range(m,n) if all(i%j !=0 for j in range(2,int(i**0.5) + 1))]

print(primes)

TRIG

Why the moon and the sun seem to be the same size in the sky:

import math
Diameter_moon=2159
Distance_moon=238855
Diameter_sun=864938
Distance_sun=92955807
print (math.degrees(math.atan2(Diameter_moon,Distance_moon)))
print (math.degrees(math.atan2(Diameter_sun,Distance_sun)))

 

With Python find the shortest routes in a network of nearby stars:

#!/usr/bin/python

import math

a=["Sol","A Centauri","E Eridani","61 Cygni","E Indi","Tau Ceti","40 Eridani"]
x=[0,-1.643,6.197,6.489,5.658,10.28,7.195]
y=[0,1.374,8.294,-6.109,-3.157,5.018,14.63]
z=[0,-3.838,-1.725,7.152,-9.896,-3.267,-2.191]

for i in range(0,6):
    for w in range(i+1,6):
        print round(math.sqrt((x[i]-x[w])**2 + (y[i]-y[w])**2 + (z[i]-z[w])**2),3),"light-years from ", a[i],"to", a[w]


Calculate the date of Easter, accurate from 1900 to 2368 inclusive.

Easter is celebrated on the first Sunday after the first full moon on or after 21 March.

#!/usr/bin/python3

import sys

y=int(sys.argv[1]) 

c=y//100;n=y-19*(y//19);k=(c-17)//25;i=c-c//4-(c-k)//3+19*n+15
i=i-30*(i//30);i=i-(i//28)*(1-(i//28)*(29//(i+1))*((21-n)//11))
j=y+y//4+i+2-c+c//4;j=j-7*(j//7);l=i-j;m=3+(l+40)//44;d=l+28-31*(m//4)
print (m,d,y,sep="/")

Print a range of Unicode characters

#!/usr/bin/python
import sys
a = int(sys.argv[1])
b = int(sys.argv[2])
for i in range(a,b + 1):
    print(" ".join([str(i)," ",unichr(i)]))


Spell out numbers

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


Find the point of intersection of two co-planar lines defined by four points

import numpy as np
A = np.array([[4,0],[4,-3]])
B = np.array([[6,2],[10,2]])
t,s = np.linalg.solve(np.array([A[1]-A[0],B[0]-B[1]]).T, B[0]-A[0])
print((1-t)*A[0]+t*A[1])


Calculate the gamma function over a range

#!/usr/bin/python

import sys
import math
from numpy import arange

start = float(sys.argv[1])
stop = float(sys.argv[2])
step = float(sys.argv[3])

for x in arange(start, stop, step):
    print (round(x,2),round(math.gamma(x),8))