Last active
May 19, 2016 00:31
-
-
Save beefy/75edcad0abb54c64270d817a6233c142 to your computer and use it in GitHub Desktop.
Python mathy functions, in no particular order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import operator | |
# primality test | |
def is_prime(i): | |
if i <= 1: return False | |
if i <= 3: return True | |
if i%3 == 0 or i%2 == 0: return False | |
return sum((1 for y in xrange(5, int(i**0.5)+1, 6) if i%y == 0 or i%(y+2) == 0)) == 0 | |
# traditional generator | |
# generate primes up to i | |
def prime_gen(i): | |
num = 2 | |
while num < i: | |
yield num | |
num += 1 | |
while not is_prime(num): | |
num += 1 | |
# like itertools.count but only for primes | |
def infinite_prime_gen(num=2): | |
while True: | |
yield num | |
num += 1 | |
while not is_prime(num): | |
num += 1 | |
# faster prime "generator", returns list | |
prime_gen_memo_arr = [2] | |
def prime_gen_memo(i): | |
while prime_gen_memo_arr[-1] < i: | |
num = prime_gen_memo_arr[-1]+1 | |
while not is_prime(num): | |
num += 1 | |
prime_gen_memo_arr.append(num) | |
return prime_gen_memo_arr | |
# returns a list of factors, including 1 and n, non distinct | |
def get_factors(n): | |
return list(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5)+1) if n % i == 0))) | |
def prod(factors): | |
return reduce(operator.mul, factors, 1) | |
factorial = lambda num : prod([i for i in range(1,num+1)]) | |
reverse_digits = lambda n: int(''.join(list([i for i in str(n)][::-1]))) | |
is_palindrome = lambda n: str(n) == str(n)[::-1] | |
# babylonian/hero's method | |
# for positive i | |
# alternative to gmpy.is_square(i) | |
def is_square(i): | |
x = i//2 | |
last = x | |
while x*x != i: | |
x = (x + (i//x))//2 | |
if last == x: | |
return False | |
last = x | |
return True | |
# long division for an arbitrary amount of precision | |
def long_divide(n, d, num_digits): | |
dividend = n | |
divisor = d | |
count = 0 | |
while dividend: | |
quotient = dividend // divisor | |
yield quotient | |
dividend = dividend % divisor * 10 | |
if count >= num_digits: | |
return | |
count += 1 | |
# Euclidean Alg for finding Greatest Common Divisor | |
# http://codereview.stackexchange.com/questions/66450/simplify-a-fraction | |
# (dev in progress) | |
def gcd(a,b): | |
q = 0 | |
r = 1 | |
while r != 0: | |
q, r = a//b, a%b | |
a, b = b, r | |
return q |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment