linkedin sandra-acebes mail google github
abrir

Python

Mathematics and Python

Mathematics and Python Programming

In [ ]:
# This book contains the following functions: 
#(i) Check Prime number; 
#(ii) Sieve of Eratostenes; 
#(iii) Factorial numbers; 
#(iv) Fibonacci sequence; 
#(v) Decimal to binary numbers and viceversa;

1.- Check if a given number is prime

In [48]:
def check_prime(number):    #Check if a given number is prime
    prime = False
    cont=0
    for i in range(2,number):
        if(number%i==0):
            cont+=1
            if cont>1:
                prime = False

    if cont<=1:
        print 'prime', number
        prime = True
    return prime

#Example
check_prime(12)
prime 11
Out[48]:
False

2.- Sieve of Eratostenes (all prime numbers up to any given)

In [ ]:
# The sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up
# to any given limit. It is an iterative process that finds any prime number. 
# The sieve stops when the square of the number is higher than the last number checked. 
# For example: For computing prime numbers between 1 and 100, I should stop in 11. 
# Remember: a number is prime only if it is divisible by one and the number itself. 

# A.- FIRST, compute all the no prime numbers (function noPrime)
# B.- SECOND, check all the numbers in the no prime list
In [36]:
import math

def allPrime(n):  #List all prime numbers until n using the Sieve of Eratostenes
    noprime = []
    all_prime = []
    n_max=int(math.sqrt(n)+1)  #The sieve will stop in this number 

    # A.-  Find all the no prime numbers in a given range 
    #create a list of no prime numbers (by multiplying )
    for j in range(2,n_max):
        for k in range(2,n):
            if j*k<n:
                noprime.append(j*k) #It generates a list of no prime numbers
    noprime_list = list(set(noprime))  #"set" orders and removes duplicates

    # B.- Check all the numbers not in the noprime list
    for z in range(1,n):
        if not z in noprime_list:
            all_prime.append(z)

    #return noprime_list, all_prime  
    return all_prime

#Example
allPrime(20)
Out[36]:
[1, 2, 3, 5, 7, 11, 13, 17, 19]

3.- Factorial Numbers

In [ ]:
# The factorial of n is the product of all positive integers less than or equal to n
In [37]:
def factorial(integer):  #Computes the factorial of n
    result=integer
    for y in range(integer-1,1,-1):
        result=result*y
    return result

#Example
factorial(8)

Out[37]:
40320

4.- Fibonacci

In [ ]:
#Fibonacci sequence: each number is the sum of the two preceding ones, starting from 0 and 1. 
In [41]:
from math import sqrt

def Fibo(number):   #Binet form to compute the Nth term from the Fibonacci sequence 

    numerator=((1+sqrt(5))**(number))-((1-sqrt(5))**(number))
    denominator= sqrt(5)*2**number
    result=numerator/denominator
    return int(result)

#Example
Fibo(9)  #The 9th element in the sequence

#Compute the Fibonacci sequence
sequence = []
number = 9 #element
for zz in range(0,number+1):
    sequence.append(Fibo(zz))

print sequence
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

5.- Converting decimal to binary number (and viceversa)

In [ ]:
# Decimal to binary: Divide the decimal number between two; 
#if the rest is even = 0, if not =1
In [13]:
def deci_to_bi(deci):  #This function converts decimal numbers into binary ones.
    bi=[]
    while deci >=1:
        if deci%2 == 0 :
            bi.append(str(0))
        else:
            bi.append(str(1))
        deci=deci/2

    binario="".join(bi[::-1]) #join the reverse of the list
    return binario

#Example
deci_to_bi(55)
Out[13]:
'110111'
In [45]:
def bi_to_deci(bi): #This funcion converts binary numbers into decimal ones
    lista= list(str(bi))
    lista_inv = lista[::-1]  #inverse positions
    sum=0
    for position, item in enumerate(lista_inv):
        sum=sum+int(item)*2**position
    return sum

#Example       
bi_to_deci(101011) #esta ignorando el ultimo cero
Out[45]:
43
In [ ]:
# Functions bin() and int()   # Transform binary and decimal numbers
In [43]:
number = 101011
#Convert binary Numbers into decimal ones
print int(str(number),2)
43
In [44]:
number = 43
#Convert decimal numbers into binary ones
print int(bin(number)[2:])
101011
In [ ]: