Python

From CleanPosts

Jump to: navigation, search


Contents

Arc length of a parabola

#!/usr/bin/python3

import math

h = float(input("Enter parabola height: "))
w = float(input("Enter parabola width: "))

l = math.log(((4 * h) + math.sqrt(w**2+ 16 * h**2)) / w) * w**2 / (8 * h) + (math.sqrt((w**2 + 16 * h **2))) / 2

print(f"Parabola arc length = {l}")

Build a sorted list of files from the current directory in python

python -c 'import glob; dir = glob.glob("*"); dir.sort(); print "\n".join((dir))'

Calculate absolute magnitude from visual magnitude and radial distance in light-years

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

Calculate days between two dates (accounts for leap years)

#!/usr/bin/python

import sys
from datetime import date

y1=int(sys.argv[1])
m1=int(sys.argv[2])
d1=int(sys.argv[3])
y2=int(sys.argv[4])
m2=int(sys.argv[5])
d2=int(sys.argv[6])

x = date(y1,m1,d1)
y = date(y2,m2,d2)
z = y - x
print (z.days)

Calculate Pi using Nilakantha's series

#!/usr/bin/python

from decimal import *
import sys

getcontext().prec = 40

c = 0
s = Decimal(1);  
pi = Decimal(3); 

n = int(sys.argv[1])

for i in range(2, n * 2, 2):
    pi = pi + s * (Decimal(4) / (Decimal(i) * (Decimal(i) + Decimal(1)) * (Decimal(i) + Decimal(2))))
    s = -1 * s
    c = c + 1
    print c, (pi)

Calculate the convergent factorial series ∑1/𝑛! = 1/1! + 1/2! + 1/3!+...

#!/usr/bin/python
import sys
import math

n = 1
for x in range (1, int(sys.argv[1])):
    n = n + (1 / float(math.factorial(x)))
    print (n)

Calculate the factors of a number in Python

#!/usr/bin/python 

import sys 

n=int(sys.argv[1]) 

factors = [] 

for i in range(1,n+1): 
    if n%i == 0: 
        factors.append(i) 

print (factors)


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))


Convert polar coordinates (right ascension, declination) to Cartesian coordinates (x,y,z)

#!/usr/bin/python

import math
import sys

rah=float(sys.argv[1])
ram=float(sys.argv[2])
ras=float(sys.argv[3])
ded=float(sys.argv[4])
dem=float(sys.argv[5])
des=float(sys.argv[6])
dis=float(sys.argv[7])

alpha=rah*15+ram/4+ras/240
delta=ded+dem/60+des/3600

alpharad=math.radians(alpha)
deltarad=math.radians(delta)

x=dis*math.cos(deltarad)*math.cos(alpharad)
y=dis*math.cos(deltarad)*math.sin(alpharad)
z=dis*math.sin(deltarad) 

print 'x =',x,'y =',y,'z =',z

Cosine by series

#!/usr/bin/python3

import sys
import math

x = float(sys.argv[1])

def cosine(x,y):
    cos = 0
    for n in range (y):
        cos += ((-1)**n) * (x ** (2*n)) / (math.factorial(2 * n))
    return cos

for i in range (1,16):
    print (math.cos(x),cosine(x,i))

Factorial function in python

python -c 'import math; print(math.factorial(52))'

Find all palindromic words in a file

#!/usr/bin/python

def words(fileobj):
    for line in fileobj:
        for word in line.split():
            yield word

with open("words.txt") as wordfile:
     wordgen = words(wordfile)
     for word in wordgen:
         if word == word[::-1]:
              print(word),

Find all permutations of a string

#!/usr/bin/python

import sys
from math import factorial

s = sys.argv[1]

from math import factorial 
    
def perm(s): 
    for i in range(factorial(len(s))):          
        print(''.join(s))   
        p=len(s)-1
        while (p > 0) and (s[p-1] > s[p]):        
            p=p-1
        s[p:] = reversed(s[p:]) 
        if p > 0: 
            q = p 
            while s[p-1] > s[q]:   
                q=q+1
        s[p-1],s[q]=s[q],s[p-1]
   

s = list(s) 
s.sort() 
perm(s)

Find the limit, as x approaches 0, of f(x) = tan x / x

#!/usr/bin/python2.7
import math
import numpy as np

for x in np.arange(1.0, 0, -0.01):
    print((math.tan(x))/x)

Find the mean of a set of numbers of any length

#!/usr/bin/python

from numpy import mean
import sys

figures = [float(elements) for elements in sys.argv[1:]]
average = mean(figures)
print ("The average is", round(average,4))

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

#!/usr/bin/python

import sys

def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
    d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)
    if d:
        uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d
        uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d
    else:
        return
    if not(0 <= uA <= 1 and 0 <= uB <= 1):
        return
    x = Ax1 + uA * (Ax2 - Ax1)
    y = Ay1 + uA * (Ay2 - Ay1)
 
    return x, y
 
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
d = float(sys.argv[4])
e = float(sys.argv[5])
f = float(sys.argv[6])
g = float(sys.argv[7])
h = float(sys.argv[8])

pt = line_intersect(a, b, c, d, e, f, g, h)
print(pt)

Five dolla quick pick Lotto

#!/usr/bin/python3

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

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

Hohmann time of flight, days

#!/usr/bin/python3

import sys
import math 

au = 149598023
mu = 1.32712E11
r1 = au * float(sys.argv[1])
r2 = au * float(sys.argv[2])
e = (r1 + r2)**3
f = mu * 8
i = math.pi * math.sqrt(e / f)
print (round((i / 3600 / 24),2))

Integration

Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> from scipy import integrate
>>> x = np.arange(0,10)
>>> y = np.sqrt(x)
>>> z = integrate.simps(y,x)
>>> print(z)
17.875036119764566


List the files in the working directory (Python)

>>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))

Loop through a range

#!/usr/bin/python3

for i in range(2, 9, 2):
    print("%d " % i, end="")
print("who do we appreciate?")

MAGA twitter account name generator

for ((i=1; i<=10; i+=1)); do python -c 'import random; print("PutinBot"+str(random.randint(100000,900000-1)))'; done

Print the first n Fibonacci numbers

#!/usr/bin/python

import sys

def fib(n,x=[0,1]):
   for i in range(abs(n)-1): x=[x[1],sum(x)]
   return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0
 
for i in range(1,int(sys.argv[1])): print fib(i)


Print the squares and cubes of the integers from 0 to 10

python -c 'print([i**2 for i in range(11)]);print([i**3 for i in range(11)])'

Return slope-intercept form of the equation of a line through two points

#!/usr/bin/python

import sys

x1=float(sys.argv[1])
y1=float(sys.argv[2])
x2=float(sys.argv[3])
y2=float(sys.argv[4])

m = (y2-y1)/(x2-x1)
b = y1 / (m * x1)

print 'y =',m,'x +',b

or

from sys import argv

x1, y1, x2, y2 = [float(f) for f in argv[1:]]

m = (y2 - y1) / (x2 - x1)
b = y1 / (m * x1)

print(f"y = {m} x + {b}")

Shuffle, deal 4 hands

python -c "num=['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']*4; suit=['h','d','c','s']*13; card=[x+y for x,y in zip(num, suit)]; import random as r; r.shuffle(card); print card[1:6];print card[7:12];print card[13:18];print card[18:23]"

Synodic period between two planets (how many days until the inside planet laps the outside planet)

#!/usr/bin/python

import sys 

inside = float(sys.argv[1])
outside = float(sys.argv[2])

interim1 = inside / outside
if interim1 < 1: 
   interim1 = 1 / interim1
interim2 = 1 - interim1
print ((abs(1 / interim2) + 1) * inside)

Use Heron's formula to obtain the area of any triangle with known side lengths

#!/usr/bin/python

import math
import sys

a=float(sys.argv[1])
b=float(sys.argv[2])
c=float(sys.argv[3])
s = (a + b + c) / 2
print (math.sqrt(s * (s - a) * (s - b) * (s - c)))

Use Python to calculate the date of Easter for any year

#!/usr/bin/python

import datetime
import sys
y = int(sys.argv[1])
g = y % 19
e = 0
c = y/100
h = (c-c/4-(8*c+13)/25+19*g+15)%30
i = h-(h/28)*(1-(h/28)*(29/(h+1))*((21-g)/11))
j = (y+y/4+i+2-c+c/4)%7
p = i-j+e
d = 1+(p+27+(p+6)/40)%31
m = 3+(p+26)/30
print datetime.date(y,m,d)

Use the complete elliptic integral of the 2nd kind to calculate the perimeter of an orbit

#!/usr/bin/python2.7

import sys
from scipy.special import ellipe
a=float(sys.argv[1])
b=float(sys.argv[2])
e = 1.0 - b**2 / a**2
print (4 * a * ellipe(e))
Personal tools
Strangers In Paradise