Python with Mathematics and Sequences – PART 2 & tricky cool Integer calculations

Here we will see some known and easy way of computing different mathematical and sequential things.

NOTE: This post is in continuation to the PART 1, however its not necessary to refer part I and you could take it as an independent post also.

Calculate the average of a series

# For an arbitrary sequence
def average(seq, total=0.0):
    num = 0
    for item in seq:
    total += item
    num += 1
    return total / num

# For a sequence type such as a list or a tuple
def average(seq):
    return float(sum(seq)) / len(seq)

Calculate the factorial of a number

In mathematics, the factorial of a number (that cannot be negative and must be an integer) n, denoted by n!, is the product of all positive integers less than or equal to n.

For example: 5! is 5*4*3*2*1.

import operator
def factorial(num):
    # the "1" initial value allows it to work for 0
    return reduce(operator.mul, range(1, num + 1), 1)

 Calculate the sum over a Sequences

A function that sums the values in a sequence with the built in python keyword, its name is ‘sum’.

>>> assert sum([1,2,3]) == 6

Calculate a derivative

Compute and print a derivative of the symbolic expression a x^2 + b.

Let’s say, i want the value of derivative at x=5.

from sympy import *
import numpy as np
x = Symbol('x')
y = x**2 + 1
yprime = y.diff(x)
yprime
>>> 2⋅x

f = lambdify(x, yprime, 'numpy')
f(np.ones(5))
>>> [ 2. 2. 2. 2. 2.]

 Calculate digits of pi

from sys import stdout 

scale = 10000
maxarr = 2800
arrinit = 2000
carry = 0
arr = [arrinit] * (maxarr + 1) 

for i in xrange(maxarr, 1, -14):
    total = 0
        for j in xrange(i, 0, -1):
            total = (total * j) + (scale * arr[j])
            arr[j] = total % ((j * 2) - 1)
            total = total / ((j * 2) - 1)
        stdout.write("%04d" % (carry + (total / scale)))
        carry = total % scale

 Calculate an integer square root

def isqrt(n):
    xn = 1
    xn1 = (xn + n/xn)/2
    while abs(xn1 - xn) > 1:
        xn = xn1
        xn1 = (xn + n/xn)/2
    while xn1*xn1 > n:
        xn1 -= 1
    return xn1

Calculate distance between two points on a globe

from math import radians, cos, sin, asin, sqrt

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 

    # 6367 km is the radius of the Earth
    km = 6367 * c
    return km

 Find a solution to a sudoku puzzle

The current shortest Python sudoku solver program is 178 bytes long and fits on four lines with no line longer than 80 chars. It prints the first solution only. To run, the intial layout must be given as command line argument containing 81 characters from 0-9 (0 = unknown), and the solution is returned in the same format to standard error. The input must have a valid solution.

def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])

To run, on a blank board:

python sudoku.py 000000000000000000000000000000000000000000000000000000000000000000000000000000000