강상위

Add 01_algorithm_analysis

# Created by https://www.gitignore.io/api/c++,macos,python
### C++ ###
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
### Python Patch ###
.venv/
### Python.VirtualEnv Stack ###
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
pip-selfcheck.json
# End of https://www.gitignore.io/api/c++,macos,python
# Algorithm Analysis
- hw
- lecture lab
# Algorithm Analysis - hw
- Compare sorting speed : c++ & python
- al_hw1.cpp
- al_hw1(exec)
- al_hw1.python
\ No newline at end of file
No preview for this file type
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cmath>
using namespace std;
// sorting algorithms
void mergeSort(int n, int s[]);
void merge(int h,int m, int u[], int v[], int s[]);
void exchangeSort(int n, int s[]);
// time checking algorithms
double cpu_time ( void );
void functionTimeCheck(string sort_type, int s[], int sLength);
int main() {
cout << "Problem Scale : ";
int input; // user input
cin >> input;
// create arrays
int s_merge[input];
int s_ex[input];
// create random numbers to arrays
srand(time(NULL));
for(int i=0; i<input; i++){
int rnum = rand()%1000;
s_merge[i] = rnum;
s_ex[i] = rnum;
}
// time check - merge sort
functionTimeCheck("merge",s_merge, input);
// print sorted values
/*
cout << "merge sort : [";
for(int i=0; i<input; i++){
if(i==(input-1))
cout << s_merge[i] << "]" << endl;
else
cout << s_merge[i] << ", ";
}
*/
// time check - excahnge sort
functionTimeCheck("exchange",s_ex, input);
// print sorted values
/*
cout << "exchange sort : [";
for(int i=0; i<input; i++){
if(i==(input-1))
cout << s_ex[i] << "]" << endl;
else
cout << s_ex[i] << ", ";
}
*/
return 0;
}
// Merge Sort
void mergeSort(int n, int s[]){
int h = n/2;
int m = n-h;
if(n>1) {
int leftHalf[h];
int rightHalf[m];
for(int i=0;i<h;i++)
leftHalf[i] = s[i];
for(int i=0;i<m;i++)
rightHalf[i] = s[h+i];
mergeSort(h,leftHalf);
mergeSort(m,rightHalf);
merge(h,m,leftHalf,rightHalf,s);
}
}
// merge
void merge(int h,int m, int u[], int v[], int s[]){
int i=0; int j=0; int k=0;
while(i<=h-1 and j<=m-1){
if(u[i]<v[j]){
s[k]=u[i];
i+=1;
}
else{
s[k]=v[j];
j+=1;
}
k+=1;
}
if(i>h-1){
for(int ii=j; ii<m; ii++){
s[k]=v[ii];
k += 1;
}
}
else{
for(int ii=i; ii<h; ii++){
s[k]=u[ii];
k += 1;
}
}
}
// Exchange Sort
void exchangeSort(int n, int s[]){
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
if(s[i] > s[j]){
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
}
double cpu_time ( ) {
double value;
value = ( double ) clock ( ) / ( double ) CLOCKS_PER_SEC;
return value;
}
// time check and print
void functionTimeCheck(string sort_type, int s[], int sLength){
double atime, btime;
if(sort_type == "merge"){
atime = cpu_time();
mergeSort(sLength,s);
btime = cpu_time();
cout << "merge sort : " << -atime + btime << endl;
}
else if(sort_type == "exchange"){
atime = cpu_time();
exchangeSort(sLength,s);
btime = cpu_time();
cout << "exchange sort : " << -atime + btime << endl;
}
}
import time
from random import *
# Merge Sort
def mergeSort(n, s):
h=int(n/2)
m=n-h
if(n>1):
leftHalf=s[:h]
rightHalf=s[h:]
mergeSort(h,leftHalf)
mergeSort(m,rightHalf)
merge(h,m,leftHalf,rightHalf,s)
# merge
def merge(h,m,u,v,s):
i=j=k=0
while(i<=h-1 and j<=m-1):
if(u[i]<v[j]):
s[k]=u[i]
i+=1
else:
s[k]=v[j]
j+=1
k+=1
if(i>h-1):
for ii in range (j,m):
s[k]=v[ii]
k += 1
else:
for ii in range (i,h):
s[k]=u[ii]
k += 1
# Exchange Sort
def exchangeSort(n,s) :
for i in range(n-1) :
j = i+1
while j <= n-1 :
if s[i] > s[j] :
temp = s[i]
s[i] = s[j]
s[j] = temp
j += 1
# time check function
# sort_type : merge / exchange
# s : random data set
def functionTimeCheck(sort_type, s) :
if sort_type == "merge" :
stime = time.time()
mergeSort(len(s),s)
print('merge sort : %10.5f' % (time.time()-stime))
elif sort_type == "exchange" :
stime = time.time()
exchangeSort(len(s),s)
print('exchange sort : %10.5f' % (time.time()-stime))
else :
print("invalid input")
# create random set
n = input("Problem Scale : ")
s = []
for i in range(n) :
rand_value = randint(0,1000)
s.append(rand_value)
functionTimeCheck("merge",s)
functionTimeCheck("exchange",s)
def printMatrix(d):
m = len(d)
n=len(d[0])
for i in range(0,m):
for j in range(0,n):
print("%4d" % d[i][j]," ")
print()
#print float matrix
def printMatrixF(d):
n=len(d[0])
for i in range(0,n):
for j in range(0,n):
print("%5.2f" % d[i][j]," ")
print()
def print_inOrder(root):
if not root:
return
print_inOrder(root.l_child)
print(root.data)
print_inOrder(root.r_child)
def print_preOrder(root):
if not root:
return
print(root.data)
print_preOrder(root.l_child)
print_preOrder(root.r_child)
def print_postOrder(root):
if not root:
return
print_postOrder(root.l_child)
print_postOrder(root.r_child)
print(root.data)
# Algorithm Analysis
- Lecture Lab
- lecture2_P2_dvide_conquer_mergesort1.py
- lecture2_P2_dvide_conquer_mergesort2.py
- lecture3_P2_dvide_conquer_quick.py
- lecture5_P3_dynamic_programming_bst.py
- lecture7_P4_greedy.py
- lecture8_P5_backtracking.py
- lecture9_P5_backtracking.py
- lecture10_P6_BB.py
- lecture11_P7_Sorting.py
- Import File
- P3_utility.py
- Warm Up Test Files
- test_exsort.py
- test.py
- test2.py
- Seperated Function - developing
- pythonMathLog.py
def kp(i, profit, weight):
global bestset
global maxprofit
if( weight <= W and profit >maxp):
maxp = profit
bestset = include[:]
# best = include는 best를 include의 reference로 만든다.
# 한 번 동일한 값을 가진 후 그 이후는 계속 동일함.
if(promising(i,weight,profit)):
include[i+1]=1
kp(i+1,profit+p[i+1], weight+w[i+1])
include[i+1]=0
kp(i+1,profit, weight)
def promising(i,weight,profit):
global maxprofit
if(weight >=W):
return False
else:
j=i+1
bound = profit
totweight = weight
# item이 있고 그 무게 안에서 최대의 bound를 찾고
while((j <= n-1) and (totweight + w[j] <= W)):
totweight += w[j]
bound += p[j]
j+=1
# k = j
if(j <= n-1):
bound += (W-totweight)*p[k]/w[k] # 최종 bound 검색
return bound > maxprofit
\ No newline at end of file
def insertionsort(n, s) :
for i in range(1,n) :
selected = s[i]
j = i-1
# 선택된 값과 비교해서 s[j]가 더 크면, 계속 오른쪽으로 덮어쓴다.
while(j>-1 and s[j]>selected) :
s[j+1] = s[j]
j-=1
# j가 -1로 만족못하고, 제자리 찾으면 while 나옴
s[j+1] = selected
def selectionsort(n, s) :
for i in range(0,n-1) :
# i를 기준점으로 잡고 이후 가장 작은 값과 바꾼다.
smallest = i
for j in range(i+1,n) :
# index만 기억하고 바꾸다가
if(s[j]<s[smallest]) :
smallest = j
# 마지막에 한번만 실제로 값을 바꾼다.
temp = s[smallest]
s[smallest] = s[i]
s[i] = temp
def exchangesort(n,s) :
for i in range(0,n-1) :
for j in range(i+1,n) :
# 걍 매번 바꾸는 거. 그러니 선택정렬보다는 느릴 수 밖에 없다.
if(s[i]>s[j]) :
temp = s[i]
s[i] = s[j]
s[j] = temp
def bubblesort(n,s) :
for i in range(n-1,-1,-1) :
for j in range(0,i) :
# i는 최대 index로부터 감소하면서 j는 0부터 증가하고 버블버블 비교하고 가장 마지막에는 가장 큰 값이 할당되게 된다.
if(s[j]>s[j+1]) :
temp = s[j]
s[j] = s[j+1]
s[j+1] = temp
s = [3,5,1,4,9879,8,2,55,42,6,99,99999,999,555]
# insertionsort(len(s),s)
# selectionsort(len(s),s)
# exchangesort(len(s),s)
bubblesort(len(s),s)
print(s)
def mergeSort(n, s):
h=int(n/2)
m=n-h
u=h*[0]
v=m*[0]
if(n>1):
leftHalf=s[:h]
rightHalf=s[h:]
mergeSort(h,leftHalf)
mergeSort(m,rightHalf)
merge(h,m,leftHalf,rightHalf,s)
def merge(h,m,u,v,s):
i=j=k=0
while(i<=h-1 and j<=m-1):
if(u[i]<v[j]):
s[k]=u[i]
i+=1
else:
s[k]=v[j]
j+=1
k+=1
if(i>h-1):
for ii in range (j,m):
s[k]=v[ii]
k += 1
else:
for ii in range (i,h):
s[k]=u[ii]
k += 1
s=[3,5,2,9,10,14,4,8,7]
mergeSort(9,s)
print(s)
def mergeSort2(n, s):
mp=int(n/2) #4
mp2=n-mp #5
u=mp*[0]
v=mp2*[0]
if(n>1):
leftHalf=s[:mp]
rightHalf=s[mp:]
mergeSort(mp,leftHalf)
mergeSort(mp2,rightHalf)
merge2(0,m,h-1)
# based on index
def merge2(low, mid, high):
i=j=k=0
u = high * [0]
i = low, j = mid+1, k = low
while(i<=mid and j<=high) :
if(s[i]<s[j]) :
u[k] = s[i]
i+=1
else :
u[k] = s[j]
j+=1
k+=1
if(i>mid) :
while(j<=high) :
u[k] = s[j]
j+=1
else :
while(i<=mid) :
u[k] = s[i]
i+=1
for ii in range(high+1) :
s[ii] = u[ii]
s=[3,5,2,9,10,14,4,8,7]
mergeSort2(9,s)
print(s)
def quickSort(s,low, high):
pivotPoint=-1
if(high>low):
pivotPoint= partition(s,low,high)
quickSort(s,low, pivotPoint-1)
quickSort(s,pivotPoint+1,high)
def partition(s,low,high):
pivotItem=s[low]
j=low
for i in range(low+1,high+1):
if(s[i]<pivotItem):
j+=1
temp=s[i]
s[i]=s[j]
s[j]=temp
pivotPoint=j
temp=s[low]
s[low]=s[pivotPoint]
s[pivotPoint]=temp
return pivotPoint
s=[3,5,2,9,10,14,4,8]
quickSort(s,0,7)
print(s)
\ No newline at end of file
import P3_utility
class Node:
def __init__(self,data):
self.l_child=None
self.r_child=None
self.data = data
def tree(key,r,i,j):
k=r[i][j]
if(k==0):
return
else:
p=Node(key[k])
p.l_child=tree(key,r,i,k-1)
p.r_child=tree(key,r,k+1,j)
return p
key=[" ","A","B","C","D"]
p=[0,0.375, 0.375, 0.125,0.125]
n=len(p)-1
a=[[0 for j in range(0,n+2)] for i in range(0,n+2)]
r=[[0 for j in range(0,n+2)] for i in range(0,n+2)]
for i in range (1,n+1):
a[i][i-1]=0
a[i][i]=p[i]
r[i][i]=i
r[i][i-1]=0
a[n+1][n]=0
r[n+1][n]=0
for dia in range(1,n):
for i in range(1,n-dia+1):
j=i+dia
small=1000
for k in range(i,j+1):
psum=0
for y in range(i,j+1):
psum+=p[y]
t=a[i][k-1]+a[k+1][j]+psum
if( t< small):
small = t
a[i][j]=t
r[i][j]=k
P3_utility.printMatrixF(a)
print()
P3_utility.printMatrix(r)
root=tree(key,r,1,n)
P3_utility.print_inOrder(root)
print()
P3_utility.print_preOrder(root)
inf=1000 #infinite
w=[[0,7,4,6,1],[inf,0,inf,inf,inf], [inf,2,0,5,inf], [inf,3,inf,0,inf], [inf,inf,inf,1,0]]
n=5
f=set()
touch=n*[0] #처음에는 도착전 마지막 노드가 없으므로 0번 자체
length=n*[0]
for i in range(1,n) :
length[i] = w[0][i]; #처음은 0번 노드가 도착 전 마지막 노드이므로 0번 노드에서 i까지 가는 거리 설정.
for k in range(1,n) :
minVal = 1000 #min 큰수로 지정함.
for i in range(1,n) :
if(0<=length[i] and length[i]<min) :
#처음 : 무조건 min이 교체될 것이고
#그 이후 : min보다 더 작으면 교체
min = length[i]
vnear = i #vnear는 미포함 지역에 있는 node이다.
f.add((touch[vnear],vnear)) #vnear에 연결되는 마지막 연결점과 vnear를 잇는 아크를 f에 추가.
\ No newline at end of file
def promising(i,col):
k=0
switch=True
while(k<i and switch==True):
if(col[i]==col[k] or abs(col[i]-col[k])==i-k):
switch=False
k+=1
return switch
def queens(n,i,col):
if(promising(i,col)==True):
if(i==n-1):
print(col)
return True #한가지 해만 찾아서 바로 리턴하는 것
else:
for j in range(0,n):
col[i+1]=j
#원본 코드
#queens(n,i+1,col)
if(queens(n,i+1,col)): #한가지 해만 찾아서 바로 리턴하는 것
return True
n=5
col=n*[0]
queens(n,-1,col)
import time
def promising(i,weight, total):
return ((weight+total >= W) and (weight==W or weight+w[i+1] <=W))
def s_s(i, weight, total, include):
#아주 조금 빨라지는 개선
if(weight+total == W) :
for j in range(i+1,n) :
include[j] = 1
print("sol",include)
elif(promising(i, weight, total)==True):
if(weight == W):
print("sol",include )
else:
include[i+1]=1
s_s(i+1, weight+w[i+1],total-w[i+1],include)
include[i+1]=0
s_s(i+1,weight,total-w[i+1],include)
w = 40*[0]
n=len(w)
for i in range(0,n):
w[i] = i+1
W=815
print("items =",w, "W =", W)
include = n*[0]
total=0
for k in w:
total+=k
start_t = time.time()
s_s(-1,0,total,include)
end_t = time.time()
print("time : ",str(end_t-start_t),'s')
import math
print("Finding most close integer n in n*log(n)")
print("Please enter the number of n*log(n)")
goal = input("Enter : ")
start = 1
increaseValue = 1
presentComparer = start
#increase or decrease : 0 - increase / 1 - decrease
valueIndicator = 0
while(1):
presentLogValue = presentComparer * math.log10(presentComparer)
if presentLogValue<goal and valueIndicator==1 and increaseValue==1 :
print("n : " + str(presentComparer))
print("most close number to goal : " + str(presentLogValue))
break
# save previous value befor comparer increasment
prevLogValue = presentLogValue
prevComparer = presentComparer
# comparer increasement
if valueIndicator == 0 :
presentComparer += increaseValue
elif valueIndicator == 1 :
presentComparer -= increaseValue
# indicator and increasement changing logic
if presentLogValue > goal :
valueIndicator = 1
if presentComparer/10 == increaseValue*10 :
increaseValue *= 10
elif presentLogValue < goal :
valueIndicator = 0
if presentComparer/10 >= increaseValue*10 :
increaseValue *= 10
# 10000/10= 1000 == 1000
# 86000/10= 1000 == 1000
# 100/10 = 9 <= 1 * 10
\ No newline at end of file
def avg_score(scores):
sum = 0
avg = 0
for i in scores:
sum += i
avg = sum / len(scores)
print(avg)
scores = [100,85,36,70,90]
avg_score(scores)
def inputData():
\ No newline at end of file
import time
def fib(n) :
if n==0 :
return 0
elif n==1:
return 1
else:
return fib(n-1) + fib(n-2)
def fib2(n):
f = (n+1) * [0]
f[0] = 0
if(n>0):
f[1] = 1
for i in range(2,n+1):
f[i] = f[i-1] + f[i-2]
return f[n]
for i in range(30,36):
stime = time.time()
fib(i)
print('%2d %10.5f' % (i, time.time()-stime))
for i in range(30,36):
stime = time.time()
fib2(i)
print('%2d %10.5f' % (i, time.time()-stime))
def exchangeSort(n,s) :
for i in range(n-1) :
j = i+1
while j <= n-1 :
if s[i] > s[j] :
temp = s[i]
s[i] = s[j]
s[j] = temp
j += 1
s=[4,5,345,2,10,14,90,8,7,56,333]
exchangeSort(len(s),s)
print(s)
# 2018-1st University Semester Lecture Files
- 01.Algorithm Analysis / 2018.9.14. Add / 2018.3 ~ 2018.6