Merge branch 'master' into modernize-python2-code

This commit is contained in:
cclauss 2017-12-13 16:32:28 +01:00 committed by GitHub
commit 2ed1bad747
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 1053 additions and 173 deletions

View File

@ -0,0 +1,58 @@
# server
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print 'Server listening....'
while True:
conn, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='mytext.txt'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
conn.send('Thank you for connecting')
conn.close()
# client side server
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
s.send("Hello server!")
with open('received_file', 'wb') as f:
print 'file opened'
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')

View File

@ -0,0 +1,20 @@
def modularExponential(base, power, mod):
if power < 0:
return -1
base %= mod
result = 1
while power > 0:
if power & 1:
result = (result * base) % mod
power = power >> 1
base = (base * base) % mod
return result
def main():
print(modularExponential(3, 200, 13))
if __name__ == '__main__':
main()

190
Neural_Network/bpnn.py Normal file
View File

@ -0,0 +1,190 @@
'''
A Framework of Back Propagation Neural NetworkBP model
Easy to use:
* add many layers as you want
* clearly see how the loss decreasing
Easy to expand:
* more activation functions
* more loss functions
* more optimization method
Author: Stephen Lee
Github : https://github.com/RiptideBo
Date: 2017.11.23
'''
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-1 * x))
class DenseLayer():
'''
Layers of BP neural network
'''
def __init__(self,units,activation=None,learning_rate=None,is_input_layer=False):
'''
common connected layer of bp network
:param units: numbers of neural units
:param activation: activation function
:param learning_rate: learning rate for paras
:param is_input_layer: whether it is input layer or not
'''
self.units = units
self.weight = None
self.bias = None
self.activation = activation
if learning_rate is None:
learning_rate = 0.3
self.learn_rate = learning_rate
self.is_input_layer = is_input_layer
def initializer(self,back_units):
self.weight = np.asmatrix(np.random.normal(0,0.5,(self.units,back_units)))
self.bias = np.asmatrix(np.random.normal(0,0.5,self.units)).T
if self.activation is None:
self.activation = sigmoid
def cal_gradient(self):
if self.activation == sigmoid:
gradient_mat = np.dot(self.output ,(1- self.output).T)
gradient_activation = np.diag(np.diag(gradient_mat))
else:
gradient_activation = 1
return gradient_activation
def forward_propagation(self,xdata):
self.xdata = xdata
if self.is_input_layer:
# input layer
self.wx_plus_b = xdata
self.output = xdata
return xdata
else:
self.wx_plus_b = np.dot(self.weight,self.xdata) - self.bias
self.output = self.activation(self.wx_plus_b)
return self.output
def back_propagation(self,gradient):
gradient_activation = self.cal_gradient() # i * i 维
gradient = np.asmatrix(np.dot(gradient.T,gradient_activation))
self._gradient_weight = np.asmatrix(self.xdata)
self._gradient_bias = -1
self._gradient_x = self.weight
self.gradient_weight = np.dot(gradient.T,self._gradient_weight.T)
self.gradient_bias = gradient * self._gradient_bias
self.gradient = np.dot(gradient,self._gradient_x).T
# ----------------------upgrade
# -----------the Negative gradient direction --------
self.weight = self.weight - self.learn_rate * self.gradient_weight
self.bias = self.bias - self.learn_rate * self.gradient_bias.T
return self.gradient
class BPNN():
'''
Back Propagation Neural Network model
'''
def __init__(self):
self.layers = []
self.train_mse = []
self.fig_loss = plt.figure()
self.ax_loss = self.fig_loss.add_subplot(1,1,1)
def add_layer(self,layer):
self.layers.append(layer)
def build(self):
for i,layer in enumerate(self.layers[:]):
if i < 1:
layer.is_input_layer = True
else:
layer.initializer(self.layers[i-1].units)
def summary(self):
for i,layer in enumerate(self.layers[:]):
print('------- layer %d -------'%i)
print('weight.shape ',np.shape(layer.weight))
print('bias.shape ',np.shape(layer.bias))
def train(self,xdata,ydata,train_round,accuracy):
self.train_round = train_round
self.accuracy = accuracy
self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1)
x_shape = np.shape(xdata)
for round_i in range(train_round):
all_loss = 0
for row in range(x_shape[0]):
_xdata = np.asmatrix(xdata[row,:]).T
_ydata = np.asmatrix(ydata[row,:]).T
# forward propagation
for layer in self.layers:
_xdata = layer.forward_propagation(_xdata)
loss, gradient = self.cal_loss(_ydata, _xdata)
all_loss = all_loss + loss
# back propagation
# the input_layer does not upgrade
for layer in self.layers[:0:-1]:
gradient = layer.back_propagation(gradient)
mse = all_loss/x_shape[0]
self.train_mse.append(mse)
self.plot_loss()
if mse < self.accuracy:
print('----达到精度----')
return mse
def cal_loss(self,ydata,ydata_):
self.loss = np.sum(np.power((ydata - ydata_),2))
self.loss_gradient = 2 * (ydata_ - ydata)
# vector (shape is the same as _ydata.shape)
return self.loss,self.loss_gradient
def plot_loss(self):
if self.ax_loss.lines:
self.ax_loss.lines.remove(self.ax_loss.lines[0])
self.ax_loss.plot(self.train_mse, 'r-')
plt.ion()
plt.show()
plt.pause(0.1)
def example():
x = np.random.randn(10,10)
y = np.asarray([[0.8,0.4],[0.4,0.3],[0.34,0.45],[0.67,0.32],
[0.88,0.67],[0.78,0.77],[0.55,0.66],[0.55,0.43],[0.54,0.1],
[0.1,0.5]])
model = BPNN()
model.add_layer(DenseLayer(10))
model.add_layer(DenseLayer(20))
model.add_layer(DenseLayer(30))
model.add_layer(DenseLayer(2))
model.build()
model.summary()
model.train(xdata=x,ydata=y,train_round=100,accuracy=0.01)
if __name__ == '__main__':
example()

View File

@ -1,152 +0,0 @@
#-*- coding:utf-8 -*-
'''
Author: Stephen Lee
Date: 2017.9.21
BP neural network with three layers
'''
import numpy as np
import matplotlib.pyplot as plt
class Bpnn():
def __init__(self,n_layer1,n_layer2,n_layer3,rate_w=0.3,rate_t=0.3):
'''
:param n_layer1: number of input layer
:param n_layer2: number of hiden layer
:param n_layer3: number of output layer
:param rate_w: rate of weight learning
:param rate_t: rate of threshold learning
'''
self.num1 = n_layer1
self.num2 = n_layer2
self.num3 = n_layer3
self.rate_weight = rate_w
self.rate_thre = rate_t
self.thre2 = -2*np.random.rand(self.num2)+1
self.thre3 = -2*np.random.rand(self.num3)+1
self.vji = np.mat(-2*np.random.rand(self.num2, self.num1)+1)
self.wkj = np.mat(-2*np.random.rand(self.num3, self.num2)+1)
def sig(self,x):
return 1 / (1 + np.exp(-1*x))
def sig_plain(self,x):
return 1 / (1 + np.exp(-1*x))
def do_round(self,x):
return round(x, 3)
def trian(self,patterns,data_train, data_teach, n_repeat, error_accuracy, draw_e=False):
'''
:param patterns: the number of patterns
:param data_train: training data x; numpy.ndarray
:param data_teach: training data y; numpy.ndarray
:param n_repeat: echoes
:param error_accuracy: error accuracy
:return: None
'''
data_train = np.asarray(data_train)
data_teach = np.asarray(data_teach)
# print('-------------------Start Training-------------------------')
# print(' - - Shape: Train_Data ',np.shape(data_train))
# print(' - - Shape: Teach_Data ',np.shape(data_teach))
rp = 0
all_mse = []
mse = 10000
while rp < n_repeat and mse >= error_accuracy:
alle = 0
final_out = []
for g in range(np.shape(data_train)[0]):
net_i = data_train[g]
out1 = net_i
net_j = out1 * self.vji.T - self.thre2
out2=self.sig(net_j)
net_k = out2 * self.wkj.T - self.thre3
out3 = self.sig(net_k)
# learning process
pd_k_all = np.multiply(np.multiply(out3,(1 - out3)),(data_teach[g]-out3))
pd_j_all = np.multiply(pd_k_all * self.wkj,np.multiply(out2,1-out2))
#upgrade weight
self.wkj = self.wkj + pd_k_all.T * out2 *self.rate_weight
self.vji = self.vji + pd_j_all.T * out1 * self.rate_weight
#upgrade threshold
self.thre3 = self.thre3 - pd_k_all * self.rate_thre
self.thre2 = self.thre2 - pd_j_all * self.rate_thre
#calculate sum of error
errors = np.sum(abs((data_teach[g] - out3)))
alle = alle + errors
final_out.extend(out3.getA().tolist())
final_out3 = [list(map(self.do_round,each)) for each in final_out]
rp = rp + 1
mse = alle/patterns
all_mse.append(mse)
def draw_error():
yplot = [error_accuracy for i in range(int(n_repeat * 1.2))]
plt.plot(all_mse, '+-')
plt.plot(yplot, 'r--')
plt.xlabel('Learning Times')
plt.ylabel('All_mse')
plt.grid(True,alpha = 0.7)
plt.show()
# print('------------------Training Complished---------------------')
# print(' - - Training epoch: ', rp, ' - - Mse: %.6f'%mse)
# print(' - - Last Output: ', final_out3)
if draw_e:
draw_error()
def predict(self,data_test):
'''
:param data_test: data test, numpy.ndarray
:return: predict output data
'''
data_test = np.asarray(data_test)
produce_out = []
# print('-------------------Start Testing-------------------------')
# print(' - - Shape: Test_Data ',np.shape(data_test))
# print(np.shape(data_test))
for g in range(np.shape(data_test)[0]):
net_i = data_test[g]
out1 = net_i
net_j = out1 * self.vji.T - self.thre2
out2 = self.sig(net_j)
net_k = out2 * self.wkj.T - self.thre3
out3 = self.sig(net_k)
produce_out.extend(out3.getA().tolist())
res = [list(map(self.do_round,each)) for each in produce_out]
return np.asarray(res)
def main():
#example data
data_x = [[1,2,3,4],
[5,6,7,8],
[2,2,3,4],
[7,7,8,8]]
data_y = [[1,0,0,0],
[0,1,0,0],
[0,0,1,0],
[0,0,0,1]]
test_x = [[1,2,3,4],
[3,2,3,4]]
#building network model
model = Bpnn(4,10,4)
#training the model
model.trian(patterns=4,data_train=data_x,data_teach=data_y,
n_repeat=100,error_accuracy=0.1,draw_e=True)
#predicting data
model.predict(test_x)
if __name__ == '__main__':
main()

View File

@ -13,8 +13,8 @@ try:
except NameError:
raw_input = input # Python 3
n = int(raw_input().strip())
sum=0;
num=0;
sum=0
num=0
while(1):
num+=3
if(num>=n):
@ -44,4 +44,5 @@ while(1):
if(num>=n):
break
sum+=num
print(sum);

View File

@ -14,7 +14,9 @@ except NameError:
raw_input = input # Python 3
n = int(raw_input().strip())
i=1; j=2; sum=0
i=1
j=2
sum=0
while(j<=n):
if((j&1)==0): #can also use (j%2==0)
sum+=j

View File

@ -18,7 +18,7 @@ def isprime(no):
return False
return True
max=0
maxNumber = 0
n=int(input())
if(isprime(n)):
print(n)
@ -32,8 +32,8 @@ else:
for i in range(3,n1,2):
if(n%i==0):
if(isprime(n/i)):
max=n/i
maxNumber = n/i
break
elif(isprime(i)):
max=i
print(max)
maxNumber = i
print(maxNumber)

View File

@ -4,13 +4,26 @@ A palindromic number reads the same both ways. The largest palindrome made from
Find the largest palindrome made from the product of two 3-digit numbers which is less than N.
'''
from __future__ import print_function
n=int(input())
for i in range(n-1,10000,-1):
temp=str(i)
if(temp==temp[::-1]):
j=999
while(j!=99):
if((i%j==0) and (len(str(i/j))==3)):
print(i)
limit = int(input("limit? "))
# fetchs the next number
for number in range(limit-1,10000,-1):
# converts number into string.
strNumber = str(number)
# checks whether 'strNumber' is a palindrome.
if(strNumber == strNumber[::-1]):
divisor = 999
# if 'number' is a product of two 3-digit numbers
# then number is the answer otherwise fetch next number.
while(divisor != 99):
if((number % divisor == 0) and (len(str(number / divisor)) == 3)):
print(number)
exit(0)
j-=1
divisor -=1

View File

@ -0,0 +1,16 @@
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the Nth prime number?
def isprime(number):
for i in range(2,int(number**0.5)+1):
if number%i==0:
return False
return True
n = int(input('Enter The N\'th Prime Number You Want To Get: ')) # Ask For The N'th Prime Number Wanted
primes = []
num = 2
while len(primes) < n:
if isprime(num):
primes.append(num)
num += 1
else:
num += 1
print(primes[len(primes) - 1])

View File

@ -0,0 +1,15 @@
power = int(input("Enter the power of 2: "))
num = 2**power
string_num = str(num)
list_num = list(string_num)
sum_of_num = 0
print("2 ^",power,"=",num)
for i in list_num:
sum_of_num += int(i)
print("Sum of the digits are:",sum_of_num)

View File

@ -0,0 +1,27 @@
# Finding the factorial.
def factorial(n):
fact = 1
for i in range(1,n+1):
fact *= i
return fact
# Spliting the digits and adding it.
def split_and_add(number):
sum_of_digits = 0
while(number>0):
last_digit = number % 10
sum_of_digits += last_digit
number = int(number/10) # Removing the last_digit from the given number.
return sum_of_digits
# Taking the user input.
number = int(input("Enter the Number: "))
# Assigning the factorial from the factorial function.
factorial = factorial(number)
# Spliting and adding the factorial into answer.
answer = split_and_add(factorial)
# Printing the answer.
print(answer)

View File

@ -0,0 +1,34 @@
def main():
"""
Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100?
"""
collectPowers = set()
currentPow = 0
N = 101 # maximum limit
for a in range(2,N):
for b in range (2,N):
currentPow = a**b # calculates the current power
collectPowers.add(currentPow) # adds the result to the set
print "Number of terms ", len(collectPowers)
if __name__ == '__main__':
main()

View File

@ -49,3 +49,10 @@ PROBLEMS:
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
Which starting number, under one million, produces the longest chain?
16. 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
20. n! means n × (n 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!

View File

@ -0,0 +1,29 @@
"""
https://www.hackerrank.com/challenges/abbr/problem
You can perform the following operation on some string, :
1. Capitalize zero or more of 's lowercase letters at some index i
(i.e., make them uppercase).
2. Delete all of the remaining lowercase letters in .
Example:
a=daBcd and b="ABC"
daBcd -> capitalize a and c(dABCd) -> remove d (ABC)
"""
def abbr(a, b):
n = len(a)
m = len(b)
dp = [[False for _ in range(m + 1)] for _ in range(n + 1)]
dp[0][0] = True
for i in range(n):
for j in range(m + 1):
if dp[i][j]:
if j < m and a[i].upper() == b[j]:
dp[i + 1][j + 1] = True
if a[i].islower():
dp[i + 1][j] = True
return dp[n][m]
if __name__ == "__main__":
print abbr("daBcd", "ABC") # expect True

View File

@ -20,7 +20,7 @@ def findMin(arr):
if (arr[i-1] <= j):
dp[i][j] = dp[i][j] or dp[i-1][j-arr[i-1]]
for j in range(s/2, -1, -1):
for j in range(int(s/2), -1, -1):
if dp[n][j] == True:
diff = s-2*j
break;

15
machine_learning/scoring_functions.py Normal file → Executable file
View File

@ -61,3 +61,18 @@ def rmsle(predict, actual):
score = np.sqrt(mean_square_diff)
return score
#Mean Bias Deviation
def mbd(predict, actual):
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
numerator = np.sum(difference) / len(predict)
denumerator = np.sum(actual) / len(predict)
print str(numerator)
print str(denumerator)
score = float(numerator) / denumerator * 100
return score

605
other/primelib.py Normal file
View File

@ -0,0 +1,605 @@
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 5 16:44:23 2017
@author: Christian Bender
This python library contains some useful functions to deal with
prime numbers and whole numbers.
Overview:
isPrime(number)
sieveEr(N)
getPrimeNumbers(N)
primeFactorization(number)
greatestPrimeFactor(number)
smallestPrimeFactor(number)
getPrime(n)
getPrimesBetween(pNumber1, pNumber2)
----
isEven(number)
isOdd(number)
gcd(number1, number2) // greatest common divisor
kgV(number1, number2) // least common multiple
getDivisors(number) // all divisors of 'number' inclusive 1, number
isPerfectNumber(number)
NEW-FUNCTIONS
simplifyFraction(numerator, denominator)
factorial (n) // n!
fib (n) // calculate the n-th fibonacci term.
-----
goldbach(number) // Goldbach's assumption
"""
def isPrime(number):
"""
input: positive integer 'number'
returns true if 'number' is prime otherwise false.
"""
import math # for function sqrt
# precondition
assert isinstance(number,int) and (number >= 0) , \
"'number' must been an int and positive"
status = True
# 0 and 1 are none primes.
if number <= 1:
status = False
for divisor in range(2,int(round(math.sqrt(number)))+1):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
status = False
break
# precondition
assert isinstance(status,bool), "'status' must been from type bool"
return status
# ------------------------------------------
def sieveEr(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N.
This function implements the algorithm called
sieve of erathostenes.
"""
# precondition
assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2"
# beginList: conatins all natural numbers from 2 upt to N
beginList = [x for x in range(2,N+1)]
ans = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(beginList)):
for j in range(i+1,len(beginList)):
if (beginList[i] != 0) and \
(beginList[j] % beginList[i] == 0):
beginList[j] = 0
# filters actual prime numbers.
ans = [x for x in beginList if x != 0]
# precondition
assert isinstance(ans,list), "'ans' must been from type list"
return ans
# --------------------------------
def getPrimeNumbers(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N (inclusive)
This function is more efficient as function 'sieveEr(...)'
"""
# precondition
assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2"
ans = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2,N+1):
if isPrime(number):
ans.append(number)
# precondition
assert isinstance(ans,list), "'ans' must been from type list"
return ans
# -----------------------------------------
def primeFactorization(number):
"""
input: positive integer 'number'
returns a list of the prime number factors of 'number'
"""
import math # for function sqrt
# precondition
assert isinstance(number,int) and number >= 0, \
"'number' must been an int and >= 0"
ans = [] # this list will be returns of the function.
# potential prime number factors.
factor = 2
quotient = number
if number == 0 or number == 1:
ans.append(number)
# if 'number' not prime then builds the prime factorization of 'number'
elif not isPrime(number):
while (quotient != 1):
if isPrime(factor) and (quotient % factor == 0):
ans.append(factor)
quotient /= factor
else:
factor += 1
else:
ans.append(number)
# precondition
assert isinstance(ans,list), "'ans' must been from type list"
return ans
# -----------------------------------------
def greatestPrimeFactor(number):
"""
input: positive integer 'number' >= 0
returns the greatest prime number factor of 'number'
"""
# precondition
assert isinstance(number,int) and (number >= 0), \
"'number' bust been an int and >= 0"
ans = 0
# prime factorization of 'number'
primeFactors = primeFactorization(number)
ans = max(primeFactors)
# precondition
assert isinstance(ans,int), "'ans' must been from type int"
return ans
# ----------------------------------------------
def smallestPrimeFactor(number):
"""
input: integer 'number' >= 0
returns the smallest prime number factor of 'number'
"""
# precondition
assert isinstance(number,int) and (number >= 0), \
"'number' bust been an int and >= 0"
ans = 0
# prime factorization of 'number'
primeFactors = primeFactorization(number)
ans = min(primeFactors)
# precondition
assert isinstance(ans,int), "'ans' must been from type int"
return ans
# ----------------------
def isEven(number):
"""
input: integer 'number'
returns true if 'number' is even, otherwise false.
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 == 0, bool), "compare bust been from type bool"
return number % 2 == 0
# ------------------------
def isOdd(number):
"""
input: integer 'number'
returns true if 'number' is odd, otherwise false.
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 != 0, bool), "compare bust been from type bool"
return number % 2 != 0
# ------------------------
def goldbach(number):
"""
Goldbach's assumption
input: a even positive integer 'number' > 2
returns a list of two prime numbers whose sum is equal to 'number'
"""
# precondition
assert isinstance(number,int) and (number > 2) and isEven(number), \
"'number' must been an int, even and > 2"
ans = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
primeNumbers = getPrimeNumbers(number)
lenPN = len(primeNumbers)
# run variable for while-loops.
i = 0
j = 1
# exit variable. for break up the loops
loop = True
while (i < lenPN and loop):
j = i+1;
while (j < lenPN and loop):
if primeNumbers[i] + primeNumbers[j] == number:
loop = False
ans.append(primeNumbers[i])
ans.append(primeNumbers[j])
j += 1;
i += 1
# precondition
assert isinstance(ans,list) and (len(ans) == 2) and \
(ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \
"'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
# ----------------------------------------------
def gcd(number1,number2):
"""
Greatest common divisor
input: two positive integer 'number1' and 'number2'
returns the greatest common divisor of 'number1' and 'number2'
"""
# precondition
assert isinstance(number1,int) and isinstance(number2,int) \
and (number1 >= 0) and (number2 >= 0), \
"'number1' and 'number2' must been positive integer."
rest = 0
while number2 != 0:
rest = number1 % number2
number1 = number2
number2 = rest
# precondition
assert isinstance(number1,int) and (number1 >= 0), \
"'number' must been from type int and positive"
return number1
# ----------------------------------------------------
def kgV(number1, number2):
"""
Least common multiple
input: two positive integer 'number1' and 'number2'
returns the least common multiple of 'number1' and 'number2'
"""
# precondition
assert isinstance(number1,int) and isinstance(number2,int) \
and (number1 >= 1) and (number2 >= 1), \
"'number1' and 'number2' must been positive integer."
ans = 1 # actual answer that will be return.
# for kgV (x,1)
if number1 > 1 and number2 > 1:
# builds the prime factorization of 'number1' and 'number2'
primeFac1 = primeFactorization(number1)
primeFac2 = primeFactorization(number2)
elif number1 == 1 or number2 == 1:
primeFac1 = []
primeFac2 = []
ans = max(number1,number2)
count1 = 0
count2 = 0
done = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in primeFac1:
if n not in done:
if n in primeFac2:
count1 = primeFac1.count(n)
count2 = primeFac2.count(n)
for i in range(max(count1,count2)):
ans *= n
else:
count1 = primeFac1.count(n)
for i in range(count1):
ans *= n
done.append(n)
# iterates through primeFac2
for n in primeFac2:
if n not in done:
count2 = primeFac2.count(n)
for i in range(count2):
ans *= n
done.append(n)
# precondition
assert isinstance(ans,int) and (ans >= 0), \
"'ans' must been from type int and positive"
return ans
# ----------------------------------
def getPrime(n):
"""
Gets the n-th prime number.
input: positive integer 'n' >= 0
returns the n-th prime number, beginning at index 0
"""
# precondition
assert isinstance(n,int) and (n >= 0), "'number' must been a positive int"
index = 0
ans = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not isPrime(ans):
ans += 1
# precondition
assert isinstance(ans,int) and isPrime(ans), \
"'ans' must been a prime number and from type int"
return ans
# ---------------------------------------------------
def getPrimesBetween(pNumber1, pNumber2):
"""
input: prime numbers 'pNumber1' and 'pNumber2'
pNumber1 < pNumber2
returns a list of all prime numbers between 'pNumber1' (exclusiv)
and 'pNumber2' (exclusiv)
"""
# precondition
assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \
"The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
number = pNumber1 + 1 # jump to the next number
ans = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not isPrime(number):
number += 1
while number < pNumber2:
ans.append(number)
number += 1
# fetch the next prime number.
while not isPrime(number):
number += 1
# precondition
assert isinstance(ans,list) and ans[0] != pNumber1 \
and ans[len(ans)-1] != pNumber2, \
"'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
# ----------------------------------------------------
def getDivisors(n):
"""
input: positive integer 'n' >= 1
returns all divisors of n (inclusive 1 and 'n')
"""
# precondition
assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1"
from math import sqrt
ans = [] # will be returned.
for divisor in range(1,n+1):
if n % divisor == 0:
ans.append(divisor)
#precondition
assert ans[0] == 1 and ans[len(ans)-1] == n, \
"Error in function getDivisiors(...)"
return ans
# ----------------------------------------------------
def isPerfectNumber(number):
"""
input: positive integer 'number' > 1
returns true if 'number' is a perfect number otherwise false.
"""
# precondition
assert isinstance(number,int) and (number > 1), \
"'number' must been an int and >= 1"
divisors = getDivisors(number)
# precondition
assert isinstance(divisors,list) and(divisors[0] == 1) and \
(divisors[len(divisors)-1] == number), \
"Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1]) == number
# ------------------------------------------------------------
def simplifyFraction(numerator, denominator):
"""
input: two integer 'numerator' and 'denominator'
assumes: 'denominator' != 0
returns: a tuple with simplify numerator and denominator.
"""
# precondition
assert isinstance(numerator, int) and isinstance(denominator,int) \
and (denominator != 0), \
"The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
gcdOfFraction = gcd(abs(numerator), abs(denominator))
# precondition
assert isinstance(gcdOfFraction, int) and (numerator % gcdOfFraction == 0) \
and (denominator % gcdOfFraction == 0), \
"Error in function gcd(...,...)"
return (numerator // gcdOfFraction, denominator // gcdOfFraction)
# -----------------------------------------------------------------
def factorial(n):
"""
input: positive integer 'n'
returns the factorial of 'n' (n!)
"""
# precondition
assert isinstance(n,int) and (n >= 0), "'n' must been a int and >= 0"
ans = 1 # this will be return.
for factor in range(1,n+1):
ans *= factor
return ans
# -------------------------------------------------------------------
def fib(n):
"""
input: positive integer 'n'
returns the n-th fibonacci term , indexing by 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
tmp = 0
fib1 = 1
ans = 1 # this will be return
for i in range(n-1):
tmp = ans
ans += fib1
fib1 = tmp
return ans

View File

@ -1,15 +1,15 @@
#Normal Distribution QuickSort
# Normal Distribution QuickSort
Algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution.
This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one.
##Array Elements
## Array Elements
The array elements are taken from a Standard Normal Distribution , having mean = 0 and standard deviation 1.
####The code
#### The code
```python
@ -52,7 +52,7 @@ The array elements are taken from a Standard Normal Distribution , having mean =
--
##Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort
## Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort
```python
>>>import matplotlib.pyplot as plt