반응형

정렬 알고리즘을 구현해 보고, 성능을 비교해 보자.
대략적으로 성능이 좋지 않은 순서대로 해 보겠다.

Selection Sort

복잡도: O(n^2)

아무 생각없이 바로 만들 수 있는 sorting 코드.
이중 루프를 돌면서 왼쪽부터 가장 작은 값을 찾아 넣음. (크면 바꾼다. swap 이것을 계속 반복하면 가장 작은 값이 index 0에 들어가게 된다.)
(일반적으로 성능 상관없이 정렬 작업할 때)

루프가 하나 끝나면 index 0가 최소값이 되고, 다음 루프로 index 1에 그 다음 작은 값이 들어가는 것을 반복한다.

-> 루프 0
index 0자리를 선택하여 나머지 전체에서 가장 작은 값을 넣고, (n-1번 비교)
index 0를 선택한 것을 index 1 부터 n-1까지 비교하면서 작은값이 있으면 swap. ; n-1인덱스에 가장 큰값이 이동됨.
-> 루프 1
index 1을 선택하여 그 다음 작은 값을 찾아 넣고. (n-2번 비교)
index 1을 선택한 것을 index 2부터 n-1까지 비교. ; n-2인덱스에 그 다음으로 큰 값이 이동됨.
...

ex)
loop i=0. j=1-4
5 1 9 3 4 : 인덱스 0, 1을 비교하여 대소위치 변경. swap
1 5 9 3 4 : 인덱스 0, 2를 비교하여 대소위치 변경
1 5 9 3 4 : 인덱스 0, 3를 비교하여 대소위치 변경
1 5 9 3 4 : 인덱스 0, 4를 비교하여 대소위치 변경
1 5 9 3 4 : 결과
인덱스0에 가장 작은 값 찾기 완료.
loop i=1. j=2-4
1 5 9 3 4 : 인덱스 1, 2을 비교하여 대소위치 변경
1 5 9 3 4 : 인덱스 1, 3를 비교하여 대소위치 변경 swap
1 3 9 5 4 : 인덱스 1, 4를 비교하여 대소위치 변경
1 3 9 5 4 : 결과
인덱스1에 2번째 작은 값 찾기 완료.
...
(왼쪽부터 위치를 하나 찍고 이후 나머지 것들과 모두 비교. 오른쪽으로 한 칸씩 이동)


void selection_sort(int arr[], int size) {
    for(int i = 0 ; i < size - 1 ; i++) 
        for (int j = i + 1 ; j < size ; j++) 
            if(arr[i] > arr[j]) {
                // swap(arr[i], arr[j]);
                int t = arr[i] ;
                arr[i] = arr[j] ;
                arr[j] = t ;
            }
}

'Develop > C&CPP' 카테고리의 다른 글

[알고리즘] 정렬3: Insertion sort  (0) 2019.12.15
[알고리즘] 정렬2: bubble sort  (0) 2019.12.13
ASN.1c  (0) 2019.08.01
벡터 구조체 필드 기준으로 최대값 최소값 찾기  (0) 2019.05.31
smart pointer 스마트포인터?  (0) 2018.07.19
반응형
derivative_br_91

91. ddxx3,definition\frac{d}{dx}x^3, definition

ddxx3=limh0(x+h)3x3h=3hx2+3h2x+h3h=limh03x2+3hx+h2=3x2 \begin{aligned} &\frac{d}{dx}x^3\\ &=\lim_{h\to0}\frac{(x+h)^3-x^3}{h}=\frac{3hx^2+3h^2x+h^3}{h}\\ &=\lim_{h\to0}3x^2+3hx+h^2=3x^2 \end{aligned}


92. ddx3x+1,def.\frac{d}{dx} \sqrt{3x+1}, def.

ddx3x+1=limh03(x+h)+13x+1h=limh0(3x+3h+1)(3x+1)h(3x+3h+1+3x+1)=limh03(3x+3h+1+3x+1)=323x+1 \begin{aligned} &\frac{d}{dx} \sqrt{3x+1}\\ &=\lim_{h\to0} \frac{\sqrt{3(x+h)+1}-\sqrt{3x+1}}{h}\\ &=\lim_{h\to0} \frac{(3x+3h+1)-(3x+1)}{h(\sqrt{3x+3h+1}+\sqrt{3x+1})}\\ &=\lim_{h\to0}\frac{3}{(\sqrt{3x+3h+1}+\sqrt{3x+1})}\\ &=\frac{3}{2\sqrt{3x+1}} \end{aligned}


93. ddx12x+5,def.\frac{d}{dx} \frac{1}{2x+5}, def.

ddx12x+5=limh012(x+h)+512x+5h=2h(2x+2h+5)(2x+5)h=limh02(2x+2h+5)(2x+5)=2(2x+5)2 \begin{aligned} &\frac{d}{dx} \frac{1}{2x+5}\\ &=\lim_{h\to0} \frac{\frac{1}{2(x+h)+5}-\frac{1}{2x+5}}{h}=\frac{ \frac{-2h}{(2x+2h+5)(2x+5)}}{h}\\ &=\lim_{h\to0} -\frac{2}{(2x+2h+5)(2x+5)}\\ &=-\frac{2}{(2x+5)^2} \end{aligned}


94. ddx1x2,def.\frac{d}{dx}\frac{1}{x^2}, def.

ddx1x2=limh01(x+h)21x2h=2xhh2x2(x+h)2h=2xhx2(x+h)2=2xx4=2x3 \begin{aligned} &\frac{d}{dx}\frac{1}{x^2}\\ &=\lim_{h\to0} \frac{\frac{1}{(x+h)^2}-\frac{1}{x^2}}{h}= \frac{\frac{-2xh-h^2}{x^2(x+h)^2}}{h}=\frac{-2x-h}{x^2(x+h)^2}\\ &=\frac{-2x}{x^4}=-\frac{2}{x^3} \end{aligned}


95. ddxsinx,def.\frac{d}{dx}sinx, def.

ddxsinx=limh0sin(x+h)sin(x)h=limh0sin(x)cos(h)+cos(x)sin(h)sin(x)h=limh0sinx(cos(h)1)h+cos(x)sin(h)hcos(h)=1h22!+h44!...limh0cos(h)1h=hc+h3c+..=O(h)=0sin(h)=hh33!+...limh0sin(h)h=1O(h2)=1=sin(x)0+cos(x)1=cos(x) \begin{aligned} &\frac{d}{dx} sinx=\lim_{h\to0} \frac{sin(x+h)-sin(x)}{h}\\ &=\lim_{h\to0} \frac{ sin(x)cos(h)+cos(x)sin(h)-sin(x)}{h}\\ &=\lim_{h\to0} \frac{sinx(cos(h)-1)}{h}+cos(x)\frac{sin(h)}{h}\\ & cos(h)=1-\frac{h^2}{2!}+\frac{h^4}{4!}-...\\ & \lim_{h\to0} \frac{cos(h)-1}{h}=hc+h^3c+..=O(h)=0 \\ & sin(h)=h-\frac{h^3}{3!}+...\\ & \lim_{h\to0} \frac{sin(h)}{h}=1-O(h^2)=1\\ & \therefore =sin(x)0+cos(x)1=cos(x) \end{aligned}


96. ddxsecx,def.\frac{d}{dx}secx, def.

ddxsec(x)=limh0sec(x+h)sec(x)h=limh01/cos(x+h)1/cos(x)h=cos(x)cos(x+h)cos(x+h)cos(x)h=cos(x)cos(x)cos(h)+sin(x)sin(h)(cos(x)cos(h)sin(x)sin(h))cos(x)h=1cos(h)+tan(x)sin(h)h(cos(x)cos(h)sin(x)sin(h))=lim1cos(x)cos(h)sin(x)sin(h)(lim1cos(h)h+limtan(x)sin(h)h)=1cos(x)(0+tan(x))=sec(x)tan(x) \begin{aligned} &\frac{d}{dx}sec(x)=\lim_{h\to0}\frac{\sec(x+h)-\sec(x)}{h}\\ &=\lim_{h\to0}\frac{1/\cos(x+h)-1/\cos(x)}{h}=\frac{cos(x)-cos(x+h)}{cos(x+h)cos(x)h}\\ &=\frac{cos(x)-cos(x)cos(h)+sin(x)sin(h)}{(cos(x)cos(h)-sin(x)sin(h))cos(x)h}\\ &=\frac{1-cos(h)+tan(x)sin(h)}{h(cos(x)cos(h)-sin(x)sin(h))}\\ &=\lim \frac{1}{cos(x)cos(h)-sin(x)sin(h)} (\lim \frac{1-cos(h)}{h}+\lim \frac{tan(x)sin(h)}{h}) \\ &=\frac{1}{cos(x)}(0+tan(x))=sec(x)tan(x) \end{aligned}


97. ddxarcsinx,def.\frac{d}{dx}arcsinx, def.

ddxarcsinx=limh0arcsin(x+h)arcsin(x)h \begin{aligned} &\frac{d}{dx}arcsinx=\lim_{h\to0} \frac{arcsin(x+h)-arcsin(x)}{h}\\ \end{aligned}

fail

ddxarcsinx=limh0arcsin(x+h)arcsin(x)hsin(ab)=sinacosbsinbcosaarcsinsin(ab)=arcsin(sinacosbsinbcosa)ab=arcsin(sinacosbsinbcosa)a=arcsin(x+h),b=arcsin(x)arcsin(x+h)arcsin(x)=arcsin(sin(arcsin(x+h))cos(arcsin(x))sin(arcsin(x))cos(arcsin(x+h)))=arcsin((x+h)cos(arcsin(x))xcos(arcsin(x+h)))(cos(x)=1sin2(x))We know,limx0sinxx=1,limx0sin(x)=limx0xSo,limx0sin1(x)=limx0x=arcsin((x+h)1x2x1(x+h)2)ddxarcsinx=limh0arcsin(x+h)arcsin(x)h=limh0arcsin((x+h)1x2x1(x+h)2)h=limh0(x+h)1x2x1(x+h)2h=limh0(x+h)2(1x2)x2(1(x+h)2)h((x+h)1x2+x1(x+h)2)Numerator=(x+h)2x2(x+h)2x2+x2(x+h)2Numerator=(x+h)2x2=2xh+h2=limh02x+h(x+h)1x2+x1(x+h)2=2xx1x2+x1x2=2x2x1x2=11x2 \begin{aligned} &\frac{d}{dx}arcsinx=\lim_{h\to0} \frac{arcsin(x+h)-arcsin(x)}{h}\\ & sin(a-b) = sinacosb-sinbcosa\\ & \arcsin {sin(a-b)} = \arcsin {(sinacosb-sinbcosa)}\\ & a-b = \arcsin {(sinacosb-sinbcosa)}\\ & a=arcsin(x+h), b=arcsin(x)\\ &arcsin(x+h)-arcsin(x) = arcsin(sin(arcsin(x+h))cos(arcsin(x))-sin(arcsin(x))cos(arcsin(x+h)))\\ &=arcsin((x+h)cos(arcsin(x))-xcos(arcsin(x+h)))\\ & (cos(x) = \sqrt {1-sin^2(x)}) \\ & \text{We know,} \lim_{x\to0} \frac{sin x}{x}=1, \lim _{x\to0} sin(x) = \lim_{x\to0} x\\ &So, \lim_{x\to0} sin^{-1}(x)=\lim_{x\to0}x &=arcsin( (x+h) \sqrt{1-x^2}-x\sqrt{1-(x+h)^2} )\\ &\frac{d}{dx}arcsinx=\lim_{h\to0} \frac{arcsin(x+h)-arcsin(x)}{h}\\ &=\lim_{h\to0} \frac{arcsin( (x+h) \sqrt{1-x^2}-x\sqrt{1-(x+h)^2} )}{h}\\ &=\lim_{h\to0} \frac{ (x+h) \sqrt{1-x^2}-x\sqrt{1-(x+h)^2} }{h} \\ &=\lim_{h\to0} \frac{ (x+h)^2(1-x^2)-x^2(1-(x+h)^2)} {h ((x+h) \sqrt{1-x^2}+x\sqrt{1-(x+h)^2} )} \\ &Numerator=(x+h)^2-x^2(x+h)^2-x^2+x^2(x+h)^2\\ &Numerator=(x+h)^2-x^2=2xh+h^2\\ &=\lim_{h\to0} \frac{ 2x+h} {(x+h) \sqrt{1-x^2}+x\sqrt{1-(x+h)^2} } \\ &=\frac{2x}{x\sqrt{1-x^2}+x\sqrt{1-x^2}}=\frac{2x}{2x\sqrt{1-x^2}}\\ &=\frac{1}{\sqrt{1-x^2}} \end{aligned}


98. ddxarctanx,def.\frac{d}{dx}arctanx, def.

Try like upper case, lim tan(x)/x = 1, atan(x)/x=1

ddxarctan(x)=limh0arctan(x+h)arctan(x)htan(ab)=tan(a)tan(b)1+tan(a)tan(b)ab=arctan(tan(a)tan(b)1+tan(a)tan(b))Numerator=arctan(x+h)arctan(x)N=arctan(tan(arctan(x+h))tan(arctan(x))1+tan(arctan(x+h))tan(arctan(x)))=arctan(x+hx1+(x+h)x)=artan(h1+x2+hx)So,ddxarctan(x)=limh0arctan(x+h)arctan(x)h=limh0artan(h1+x2+hx)h=limh011+x2+hx=11+x2 \begin{aligned} &\frac{d}{dx}arctan(x)=\lim_{h\to0} \frac{arctan(x+h)-arctan(x)}{h}\\ & tan(a-b)=\frac{tan(a)-tan(b)}{1+tan(a)tan(b)}\\ & a-b = arctan(\frac{tan(a)-tan(b)}{1+tan(a)tan(b)})\\ &Numerator=arctan(x+h)-arctan(x)\\ &N=arctan( \frac{tan(arctan(x+h))-tan(arctan(x))}{1+tan(arctan(x+h))tan(arctan(x))} )\\ &=arctan( \frac{x+h-x}{1+(x+h)x} )=artan(\frac{h}{1+x^2+hx})\\ &So, \\ &\frac{d}{dx}arctan(x)=\lim_{h\to0} \frac{arctan(x+h)-arctan(x)}{h}\\ &=\lim_{h\to0} \frac{artan(\frac{h}{1+x^2+hx})}{h}\\ &=\lim_{h\to0} \frac{1}{1+x^2+hx}=\frac{1}{1+x^2}\\ \end{aligned}


99. ddxf(x)g(x),def.\frac{d}{dx}f(x)g(x), def.

ddxf(x)g(x)=limh0f(x+h)g(x+h)f(x)g(x)h=limh0f(x+h)g(x+h)f(x)g(x)g(x+h)f(x)+g(x+h)f(x)h=limh0g(x+h)(f(x+h)f(x))+f(x)(g(x+h)g(x))h=limh0g(x+h)f(x+h)f(x)h+f(x)g(x+h)g(x)h=g(x)f(x)+f(x)g(x)=f(x)g(x)+f(x)g(x) \begin{aligned} &\frac{d}{dx}f(x)g(x)=\lim_{h\to0}\frac{f(x+h)g(x+h)-f(x)g(x)}{h}\\ &=\lim_{h\to0}\frac{f(x+h)g(x+h)-f(x)g(x)-g(x+h)f(x)+g(x+h)f(x)}{h}\\ &=\lim_{h\to0} \frac{g(x+h)(f(x+h)-f(x))+f(x)(g(x+h)-g(x))}{h}\\ &=\lim_{h\to0} g(x+h)\frac{f(x+h)-f(x)}{h}+f(x)\frac{g(x+h)-g(x)}{h}\\ &=g(x)f'(x)+f(x)g'(x)=f'(x)g(x)+f(x)g'(x) \end{aligned}


100. ddxf(x)g(x),def.\frac{d}{dx} \frac{f(x)}{g(x)}, def.

ddxf(x)g(x)=limh0f(x+h)g(x+h)f(x)g(x)h=f(x+h)g(x)f(x)g(x+h)g(x)g(x+h)h=f(x+h)g(x)f(x)g(x+h)g(x)f(x)+g(x)f(x)hg(x)g(x+h)=g(x)(f(x+h)f(x))f(x)(g(x+h)g(x))hg(x)g(x+h)=g(x)f(x)f(x)g(x)g(x)2 \begin{aligned} &\frac{d}{dx} \frac{f(x)}{g(x)}=\lim_{h\to0}\frac{ \frac{f(x+h)}{g(x+h)} - \frac{f(x)}{g(x)}}{h} =\frac{ \frac{f(x+h)g(x)-f(x)g(x+h)}{g(x)g(x+h)} }{h}\\ &=\frac{ f(x+h)g(x)-f(x)g(x+h)-g(x)f(x)+g(x)f(x)}{hg(x)g(x+h)}\\ &=\frac{g(x)(f(x+h)-f(x))-f(x)(g(x+h)-g(x))}{hg(x)g(x+h)}\\ &=\frac{g(x)f'(x)-f(x)g'(x)}{g(x)^2} \end{aligned}


101. ddxxxx\frac{d}{dx} x^{{x}^{x}}

First,ddxxxy=xx,lny=xlnx,(1/y)y=lnx+x(1/x)y=ylnx+y=xxlnx+xx \frac{d}{dx}x^x\\ y=x^x, lny=xlnx, (1/y)y'=lnx+x(1/x)\\ y'=ylnx+y=x^xlnx+x^x
Second,
ddxxxxy=xxxlny=xxln(x)1yy=(xxlnx+xx)ln(x)+xx1x=xx((lnx)2+ln(x)+1x)y=xxxxx((lnx)2+ln(x)+1x) \begin{aligned} &\frac{d}{dx} x^{x^{x}}\\ &y=x^{x^{x}} \\ &ln y = x^x ln(x) \\ &\frac{1}{y} y' = (x^xlnx+x^x)ln(x)+x^x\frac{1}{x}\\ &=x^x((lnx)^2+ln(x)+\frac{1}{x})\\ &y'=x^{x^x}x^x((lnx)^2+ln(x)+\frac{1}{x})\\ \end{aligned}


The END

Author: crazyj7@gmail.com

'Math' 카테고리의 다른 글

미적분학의 본질 #2  (0) 2020.08.27
미적분학의 본질 #1  (1) 2020.08.27
Derivative100 [81-90]  (0) 2019.12.12
derivative100 [71-80]  (0) 2019.11.27
derivative100 [61-70]  (0) 2019.11.19
반응형
derivative_br_81

81. ddxexsinhx\frac{d}{dx}e^x sinhx

ddxexsinhx=exsinhx+excoshx=ex(sinhx+coshx)=ex(2ex2)=e2x \begin{aligned} &\frac{d}{dx}e^x sinhx\\ &=e^xsinhx+e^xcoshx=e^x(sinhx+coshx)\\ &=e^x(\frac{2e^x}{2})=e^{2x} \end{aligned}


82. ddxsech(1x)\frac{d}{dx}sech(\frac{1}{x})

ddxsech(1x)sech(x)=1/cosh(x),D(sech(x))=sinh(x)/cosh2(x)=sech(x)tanh(x)ddxsech(1x)=sinh(1/x)/cosh2(1/x)(1/x2)=sinh(1/x)x2cosh2(1/x)=sech(1x)tanh(1x)x2 \begin{aligned} &\frac{d}{dx}sech(\frac{1}{x})\\ & sech (x)=1/cosh(x), D(sech(x))=-sinh(x)/cosh^2(x)\\ &=-sech(x)tanh(x)\\ &\frac{d}{dx}sech(\frac{1}{x})=-sinh(1/x)/cosh^2(1/x)(-1/x^2)\\ &=\frac{sinh(1/x)}{x^2cosh^2(1/x)}=\frac{sech(\frac{1}{x})tanh(\frac{1}{x})}{x^2}\\ \end{aligned}


83. ddxcosh(lnx))\frac{d}{dx}cosh(lnx))

ddxcosh(lnx)=sinh(lnx)x=elnxelnx2x=x(1/x)2x=x212x2 \begin{aligned} &\frac{d}{dx}cosh(lnx)=\frac{sinh(lnx)}{x}=\frac{e^{lnx}-e^{-lnx}}{2x}\\ &=\frac{x-(1/x)}{2x}=\frac{x^2-1}{2x^2}\\ \end{aligned}


84. ddxln(coshx)\frac{d}{dx}ln(coshx)

ddxln(coshx)=sinhxcoshx=tanh(x) \begin{aligned} &\frac{d}{dx}ln(coshx)=\frac{sinhx}{coshx}=tanh(x)\\ \end{aligned}


85. ddxsinhx1+coshx\frac{d}{dx}\frac{sinhx}{1+coshx}

ddxsinhx1+coshx=coshx(1+coshx)sinhxsinhx1+cosh2x+2cosh(x)=coshx+cosh2xsinh2x(1+coshx)2=1+coshx(1+coshx)2=11+coshx \begin{aligned} &\frac{d}{dx}\frac{sinhx}{1+coshx}=\frac{coshx(1+coshx)-sinhxsinhx}{1+cosh^2x+2cosh(x)}\\ &=\frac{coshx+cosh^2x-sinh^2x}{(1+coshx)^2}=\frac{1+coshx}{(1+coshx)^2}\\ &=\frac{1}{1+coshx} \end{aligned}


86. ddxarctanh(cosx)\frac{d}{dx}arctanh(cosx)

ddxarctanh(cosx)D(arctanh(x))=11x2y=arctanh(x),x=tanh(y),dx=sech2(y)dydy/dx=1/sech2(y)=cosh2(y)=1(1/cosh2(y))=1(cosh2(y)sinh2(y))/cosh2(y)=11tanh2(y)=11x2ddxarctanh(cosx)=sinx1cos2x=sin(x)sin2(x)=csc(x) \begin{aligned} &\frac{d}{dx}arctanh(cosx)\\ &D(arctanh(x)) = \frac{1}{1-x^2}\\ &y=arctanh(x), x=tanh(y), dx=sech^2(y)dy\\ &dy/dx = 1/sech^2(y)=cosh^2(y)=\frac{1}{(1/cosh^2(y))}\\ &=\frac{1}{( cosh^2(y)-sinh^2(y))/cosh^2(y)}=\frac{1}{1-tanh^2(y)}\\ &=\frac{1}{1-x^2}\\ &\frac{d}{dx}arctanh(cosx)=-\frac{sinx}{1-cos^2x}\\ &=-\frac{sin(x)}{sin^2(x)}=-csc(x)\\ \end{aligned}


87. ddx(x)(arctanhx)+ln((1x2))\frac{d}{dx}(x)(arctanhx)+ln(\sqrt{(1-x^2}))

ddx(x)(arctanhx)+ln(1x2)=arctanh(x)+x11x2+11x22x21x2=arctanh(x)+x1x2x1x2=arctanh(x) \begin{aligned} &\frac{d}{dx}(x)(arctanhx)+ln(\sqrt{1-x^2})\\ &=arctanh(x)+x\frac{1}{1-x^2}+\frac{1}{\sqrt{1-x^2}}\frac{-2x}{2\sqrt{1-x^2}}\\ &=arctanh(x)+\frac{x}{1-x^2}-\frac{x}{1-x^2}\\ &=arctanh(x) \end{aligned}


88. ddxarcsinh(tanx)\frac{d}{dx}arcsinh(tanx)

ddxarcsinh(tanx)=11+tan2xsec2x=sec2xsecx=sec(x) \begin{aligned} &\frac{d}{dx}arcsinh(tanx)\\ &=\frac{1}{\sqrt{1+tan^2x}}sec^2x=\frac{sec^2x}{sec x}\\ &=sec(x) & \end{aligned}


89. ddxarcsin(tanhx)\frac{d}{dx}arcsin(tanhx)

ddxarcsin(tanhx)=11tanh2xsech2x1tanh2x=cosh2xsinh2xcosh2x=sech2x=sech2xsech2x=sech(x) \begin{aligned} &\frac{d}{dx}arcsin(tanhx)\\ &=\frac{1}{\sqrt{1-tanh^2x}} sech^2x\\ &1-tanh^2x = \frac{cosh^2x-sinh^2x}{cosh^2x}=sech^2x\\ &=\frac{sech^2x}{\sqrt {sech^2x} }=sech(x) \end{aligned}


90. ddxarctanhx1x2\frac{d}{dx} \frac{arctanhx}{1-x^2}

ddxarctanhx1x2=11x2(1x2)arctanh(x)(2x)(1x2)2=1+2xarctanh(x)(1x2)2 \begin{aligned} &\frac{d}{dx} \frac{arctanhx}{1-x^2}\\ &=\frac{\frac{1}{1-x^2}(1-x^2)-arctanh(x)(-2x)}{(1-x^2)^2} \\ &=\frac{1+2x arctanh(x)}{(1-x^2)^2} \\ \end{aligned}


Author: crazyj7@gmail.com

'Math' 카테고리의 다른 글

미적분학의 본질 #1  (1) 2020.08.27
Derivative100 [91-100]  (0) 2019.12.12
derivative100 [71-80]  (0) 2019.11.27
derivative100 [61-70]  (0) 2019.11.19
derivatie100 [51-60]  (0) 2019.11.18
반응형
remove dict key

Remove Dict Key

딕셔너리에서 키를 안전하게 삭제하는 방법.
샘플로 다음과 같은 dictionary가 있다고 하자.

dic = dict()
dic['apple']=100
dic['banana']=200
dic['orange']=300
# 간단하게 하면 
dic = {'apple':100, 'banana':200, 'orange':300 }

위에서 apple를 지워보자.

del 로 삭제할때…

만약 키가 없으면 어떻게 될까?
del dic['mango']
KeyError!
안전하게 삭제하려면

# 1안
if 'mango' in dic:
	del dic['mango']

위와 같이 존재하는지 검사한다음, 있으면 삭제하는 것으로 할 수 있다.
매번 이렇게 if를 해 주는게 귀찮긴 한데…
일단 삭제를 시도하고, 에러나면 에러 처리하도록 할 수 있다.

# 2안
try:
	del dic['mango']
except KeyError:
	pass

pop으로 삭제할때…

dict()의 pop()을 사용하면 값을 꺼내올 수 도 있고, 해당 키가 삭제되는 효과도 있다. 이것도 키가 없다면? 에러가 발생할 것 같은데…
del과 마찬가지로 KeyError 예외가 발생한다.
즉, 해결방법은 1안과 2안처럼, 존재체크를 하거나 예외 처리를 할 수 있다.

dic.pop('mango')  # mango not found -> KeyError!!!

다른 방법은???
pop()의 다른 형태로는 파라미터에 값을 추가하면 키가 없을 때 디폴트 값을 리턴하도록 하는 기능이 있다. 이 방식을 사용하면 쉽게 안전한 삭제가 가능하다.

# 3안
dic.pop('mango', None) # if not found -> None. (no error!)

이제 있을지 모르는 키를 삭제하려면 pop( [key], None)을 사용하자.

dic.pop('apple', None)

위와 같이 하면 해당 키가 존재하는지 체크를 하거나 except 처리를 할 필요가 없다.

Author: crazyj7@gmail.com

'Python' 카테고리의 다른 글

Jupyter Notebook 소스 복구  (0) 2020.06.16
Docker python venv 패키지 유지  (0) 2020.06.07
파이썬 충돌해결 module conflict  (0) 2019.12.01
파이썬 개발환경/가상환경구축  (0) 2019.12.01
진법 표현 및 수 스트링 변환  (0) 2019.11.24
반응형
XGBoost

XGBoost

eXtreme Gradient Boosting

  • 병렬 처리로 학습, 분류 속도가 빠르다.
  • 다양한 옵션. Customizing 용이
  • Greedy 알고리즘을 사용한 자동 가지치기로 오버피팅 방지가 된다.
  • 다른 알고리즘과 연계에도 성능이 좋다. 뒷단에 다른 레이어 추가.

XGBoost는 딥러닝이 아니다. 여러가지 조건문들이 들어가는 가지치기로 보면 된다. Decision Tree라고 하고 이것들이 다 모이면 최종적으로 forest라고 한다
데이터에 따라 딥러닝보다 성능이 좋은 경우가 많다.

XGBoost는 CART(Classification and regression tree) 앙상블 모델을 사용한다. 모델끼리의 우의 비교를 통해 최종 결정을 내림.

파라미터

  • 일반 파라미터 ; 어떤 모델을 쓸 것인가?
    • gbtree, gblinear, dart
    • nthread ; 쓰레드 수. 디폴트는 max
    • num_feature ; 입력 차원. 디폴트는 max
  • 부스터 파라미터 ; 트리마다 가지치기 옵션
    • eta ; learning rate. 트리에 가지가 많을수록 과적합 발생.
    • gamma ; 정보획득에서 -r. 값이 클수록 트리 depth가 줄어든다. 디폴트는 0
    • max_depth ; 한 트리의 최대 깊이. 클수록 복잡도가 커짐. 즉, 과적합. 디폴트는 6으로 리프노드의 최대개수는 64가 된다.
    • lambda ; L2 Regularization. 클수록 보수적.
    • alpha ; L1 Regularization
  • 학습 과정 파라미터 ; 최적화
    • objective ; 목적함수. reg:linear, binary:logistic, count:poisson 등
    • num_rounds : 라운드 epoch 같은 개념. 너무 커도 좋지 않다.

파라미터를 알아야 모델을 구축할 수 있다.
binary classification 문제에 linear-regression을 적용하면 아무리해도 답이 안나온다.

  • 민감한 정도로 먼저 조정해야 될 것들
    • booster 모양
    • eval_metric(평가함수)/ objective(목적함수)
    • eta (epoch)
    • L1
    • L2

Sample1. XGBClassifier

from numpy import loadtxt
from xgboost import XGBClassifier
from xgboost import plot_importance
from matplotlib import pyplot

dataset = loadtxt('pima-indians-diabetes.csv', delimiter=',')
x=dataset[:,0:8]
y=dataset[:,8]

# fit model no training data
model = XGBClassifier()
model.fit(x,y)

plot_importance(model)
pyplot.show()
  • fitting후 plot_importance로 어떤 피쳐들의 중요도를 높게 보고있는지 막대그래프로 확인할 수 있다.
  • 중요도가 크게 떨어지는 피쳐들은 삭제하는 것이 성능에 좋은 영향을 주는 경우가 많다.

Sample2. XGBRegressor

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import Imputer

# 데이터를 읽고, null 레코드 삭제
data = pd.read_csv('../input/train.csv')
data.dropna(axis=0, subset=['SalePrice'], inplace=True)
# 출력값은 집값
y = data.SalePrice
# 훈련데이터에서 집값제거하고 수치가 아닌 데이터 삭제.
X = data.drop(['SalePrice'], axis=1).select_dtypes(exclude=['object'])
# 데이터 분리. train, validation data. 
train_X, test_X, train_y, test_y = train_test_split(X.as_matrix(), y.as_matrix(), test_size=0.25)

# 데이터 전처리
my_imputer = Imputer()
train_X = my_imputer.fit_transform(train_X)
test_X = my_imputer.transform(test_X)

  • sklearn의 preprocessing에 Imputer로 데이터를 전처리 하였다.
  • Imputer?
    • 누락 NA 데이터에 대한 전처리가 가능하다.
    • 데이터 파일에서 ‘na’ 스트링을 na로 인식하여 로딩하여도록 하려면 pd.read_csv(‘test.csv’, na_values=‘na’)
  • SimpleImputrer
    -누락된 데이터의 값을 특정 값으로 지정하거나 통계값으로 설정할 수 있다.
    • imp = SimpleImputer(missing_values=np.nan, strategy=‘mean’)
    • imp.fit( data ) ; fitting하여 통계 정보를 구한다.
    • X = imp.transform( data ) ; 위 통계 정보를 사용하여 np.nan값을 컬럼마다 평균값으로 채움.
    • missing_values=-1 로 하면 -1값을 누락값으로 인식.
    • strategy의 종류 ; mean, most_frequent (최고빈도로 스트링 컬럼(category)도 처리가 됨.)
  • Imputer
    • Imputer(missing_vaues=‘NaN’, strategy=‘mean’ , axis=0, verbose=0, copy=True) ; 기본값 확인. (여기는 특이하게 axis=0이 컬럼방향이다.)
from xgboost import XGBRegressor

my_model = XGBRegressor()
# Add silent=True to avoid printing out updates with each cycle
my_model.fit(train_X, train_y, verbose=False)

# make predictions
predictions = my_model.predict(test_X)

from sklearn.metrics import mean_absolute_error
print("Mean Absolute Error : " + str(mean_absolute_error(predictions, test_y)))
  • 학습은 위와 같이 매우 간단하다.

모델 튜닝

  • 성능을 올리기 위한 필수 과정.
  • n_estimators ; 학습 횟수
  • early_stopping_rounds ; n연속으로 발전(기존 max 갱신)이 없으면 강제 중지
my_model = XGBRegressor(n_estimators=1000)
my_model.fit(train_X, train_y, early_stopping_rounds=5, 
             eval_set=[(test_X, test_y)], verbose=False)
  • learning_rate ; 학습률
my_model = XGBRegressor(n_estimators=1000, learning_rate=0.05)
my_model.fit(train_X, train_y, early_stopping_rounds=5, 
             eval_set=[(test_X, test_y)], verbose=False)
  • n_jobs ; 병렬처리로 보통 cpu core 수로 정하는 것이 좋다.

Author: crazyj7@gmail.com

'AI(DeepLearning)' 카테고리의 다른 글

[ChatGPT] 글쓰기  (0) 2023.02.09
[ChatGPT] 글쓰기 테스트  (1) 2023.02.09
처음해본 kaggle 도전기  (1) 2019.11.27
Custom EarlyStopping  (0) 2019.11.11
타이타닉 kaggle 자료 분석  (0) 2019.08.23
반응형
solidity03_data_var

Solidity 03. Variables/Datatypes

변수를 어떻게 사용하는가?

  • 멤버 변수들은 Storage 변수. 상태 변수이다.
  • 파라미터들은 Memory 변수. 함수 리턴시 날라간다.
  • 파라미터에 Storage를 지정하면? 참조가 된다?

integer와 string을 get/set 하는 예제

pragma solidity >=0.4.0 <0.6.0;

contract SimpleStorage {
    uint storedData;
    string storedNm;

    function set(uint x) public {
        storedData = x;
    }

    function setNm(string memory x) public {
        storedNm = x;
    }

    function get() public view returns (uint) {
        return storedData;
    }

    function getNm() public view returns (string memory ) {
        return storedNm;
    }
}
  • 기본 자료형이 아닌 것은 저장소를 명시해 주어야 한다. string을 사용하는 부분에 memory 타입으로 명시함.

datatype

  • 기본형
    uint/int ; uint, int는 뒤에 256이 생략되어 있다. (u는 unsigned 의미)
    uint8~uint256 ; 여기서 숫자는 비트수를 의미. 1바이트부터 32바이트까지 있다.
    bool : true or false
    byte : uint8과 같다고 생각하면 된다.
    address : 20바이트 주소값
    address payable : address타입인데 멤버함수가 있다. transfer, send.
    address payable x = address(uint160(to));

enum State { Created, Locked, Inactive } ;
산술/비교/비트/논리 연산자는 C 와 같음. enum도 같다.

  • 참조형
    배열 : [] array
    구조체: struct
0xffff ; int16(-1)
0x42 ; bytes1(0x42)
0x0003 ; uint16(0x03)
0x48656c6c6f2c20776f726c6421 ; string("Hello, world!") (without null)

address의 멤버

  • balance ; 계정 주소에 있는 이더를 wei로 반환
  • transfer(uint amount) ; 계정 주소(받는 사람 주소)에 있는 amount 금액을 송금. to.transfer(_amount)
  • send(uint amount) returns (bool) ; 상동. 실패시 false 리턴. to_send(_amount)
  • call(…) returns (bool) : 상동, 실패시 false 리턴. 가스량 조절 가능. to.call.value(_amount).gas(1000000)() . 리턴값을 확인하여 false이면 revert()로 롤백한다.
  • delegatecall(…) returns (bool) : 다른 계약의 함수를 호출.
address x=0x123 ;
address myAddress = this ;
if (x.balance<10 && myAddress.balance>=10) x.transfer(10) ;
  • send : low-level의 transfer임. (실패시 롤백없음). 리턴값(true/false)을 반드시 확인.

고정크기 바이트 배열

bytes1/bytes2/bytes3/… bytes32 : bytes뒤에 숫자를 붙인다. 바이트수를 의미.
byte : bytes1과 같다.
멤버
length : 고정된 길이를 반환. 읽기 전용.
bytes32는 32바이트까지만 담을 수 있다.
ex)
bytes2 b = “bac”

동적 크기 바이트 배열

bytes : 임의 길이의 원시데이터.
string : UTF-8 인코딩 문자열. 임의의 길이. 거의 무제한.(2^256 * 256 비트)

  • 멤버로 length, push()가 있다.
  • 작은 따옴표나 큰 따옴표 상관없다.
    ex) bytes memory a = ‘aaaaaaaaaa’;
    a.length ;
    a.push(‘c’) ;
    a.push(“C”) ;
    a.push(“AB”) ; // error. byte[]라서 byte 하나만 push 가능.

문자열 리터럴

작은 따옴표, 큰 따옴표 둘 다 가능.
C랑 다르게 null terminated가 아니다. 보이는 문자 개수만큼만 메모리를 차지함.
\n, \xNN (16진수), \uNNNN (유니코드) 도 지원.

16진수 리터럴

hex"001122FF"
앞에 hex를 지정.

이중배열

uint [][5] : 주의할 점은 행과 열이 다른 언어와 반대임.
이것을 C로 보면 uint [5][] 이 된다.

  • 웃긴건 접근할 때는 C처럼 행, 열 순으로 접근한다.
  • 선언할 때랑 사용할 때랑 다르다니 문화충격이다.
uint[3][2] dArray ;
// row index는 0,1까지 가능. column index는 0,1,2까지 가능.
// C나 java로 치면 uint dArray[2][3] 으로 생각해야 함.
dArray[1][2] = 100 ;  // last element.

dArray[2][2] = 100 ; // error. 
dArray[0][3] = 100 ; // error. 
function f(uint len) public pure {
	uint[] memory a = new uint[](7) ;
	bytes memory b = new bytes(len) ;
	// a.length==7, b.length=len
	a[6]=8 ;
}
function f() public pure {
	g([uint(1), 2, 3]) ;
}
function g(uint[3] _data) pubilc pure {
}

[1,2,3] 은 uint8[3] memory 타입이다. array에 첫 번째 요소에 타입을 명시해 줄 수 있다.

  • 고정 크기 배열을 동적크기 배열에 할당할 수 없다.!
uint8[] memory x = [uint8(1),2,3] ;	// 에러
uint8[3] memory x = [uint8(1),2,3] ;	// 가능.

uint[] dArray ;
dArray.push(2) ;
dArray.push(3) ;
  • 삭제는 delete로 배열을 삭제한다.
  • 일반 변수에 delete를 하면 초기값(0)으로 할당된다.

자료구조

struct 지원

struct Voter {
uint w ;
bool v ;
address dele ;
uint vote ;
}

Enum Types

enum State { Created, Locked, Inactive }

Type Conversion

  • uint를 스트링으로 변환. 하나씩 바이트 단위로 ascii char로 변환한다.
function uintToString(uint v) constant returns (string str) {
        uint maxlength = 100;
        bytes memory reversed = new bytes(maxlength);
        uint i = 0;
        while (v != 0) {
            uint remainder = v % 10;
            v = v / 10;
            reversed[i++] = byte(48 + remainder);
        }
        bytes memory s = new bytes(i + 1);
        for (uint j = 0; j <= i; j++) {
            s[j] = reversed[i - j];
        }
        str = string(s);
}

function uint2str(uint i) internal pure returns (string)
{ 
	if (i == 0) return "0"; 
	uint j = i; 
	uint length; 
	while (j != 0){ length++; j /= 10; } 
	bytes memory bstr = new bytes(length); 
	uint k = length - 1; 
	while (i != 0){ bstr[k--] = byte(48 + i % 10); 
	i /= 10; 
	} 
	return string(bstr); 
}
  • 타입 캐스팅은 타입을 함수처럼 사용하여 파라미터로 받는다.
  • 32비트를 16비트로 타입 캐스팅시 하위 바이트(낮은 자리 값)만 가져온다.
  • 예를 들면. uint32 a= 0x12345678 ; 이것을 uint16 b = uint16(a) ; 이렇게 하면 하위 바이트인 0x5678을 가져온다.

Mapping

contract Mappings {
 struct User {
   string name ;
   string email ;
 }
 mapping(address => User) users ;
 function addUser(string memory _name, string memory _email) public {
   users[msg.sender].name = _name ;
   users[msg.sender].email = _email ;
 }
 function getUser() public returns (string memory, string memory) {
   return (users[msg.sender].name, users[msg.sender].email) ;
 }
}

이더리움 단위

wei ; 가장 작은 단위
1000 배씩 올라간다.
kwei, mwei, gwei, micro, milli, ether
kether, mether, gether, tether
위 단위를 코드에 그대로 사용한다.
즉, 1 이더는 10**18 wei

시간 단위

second, minute, hour, day, week, year

블록 및 거래 속성

  • block.blockhash(uint blockNumber) returns (bytes32) : 지정한 블록의 해시값을 리턴. (최근 256개 블록만 사용 가능)
  • block.coinbase ; address 채굴자 계정 주소
  • block.difficulty ; uint 현재 블록 난이도
  • block.gaslimit ; uint 현재 블록의 가스 제한량
  • block.number ; uint 현재 블록 번호
  • block.timestamp ; uint 현재 블록의 타임스탬프
  • msg.data ; bytes 호출 데이터
  • msg.gas ; 남은 가스양
  • msg.sender ; address 메시지를 보낸사람
  • msg.sig ; bytes4 calldata의 첫 4바이트로 함수 식별자
  • msg.value ; uint 메시지와 같이 보낸 wei
  • now ; block.timestamp와 같다. (현재 시간을 의미하는 값은 아니다. 현재시간과 대략 비슷)
  • tx.gasprice ; uint 거래의 가스가격
  • tx.origin ; 거래 발신자 주소. (sender.address와 같을 수도 다를 수도 있다.)
  • this ; 현재 계약
  • selfdestruct(address) ; 현재 계약을 파기해 지정한 주소로 금액을 보냄
  • suicide(address) ; 상동

예외 처리

  • assert(bool condition) ; 조건이 실패하면 에러를 발생시킨다. (보통 내부에러)
  • require(bool condition) ; 위와 같다. 입력값 체크시 사용. (보통 외부에러)
  • revert() ; 에러가 발생하면 롤백을 시킨다.

기타 연산

  • addmod(uint x, uint y, uint k) returns (uint) : (x+y)%k
  • mulmod(uint x, uint y, uint k) returns (uint) : (x*y)%k
  • keccak256( data ) returns (bytes32) : 이더리움 sha3 (KECCAK256) 해시
  • sha256
  • sha3 ; keccak256과 동일
  • ripecmd160(data) returns (bytes20)
  • ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) return (address) : 타원곡선암호서명에서 공개키와 연결된 주소를 리턴

할당

  • 복수 데이터를 할당 할 수 있다. 리턴도 복수개가 가능
    • (x,y) = f() ;
  • swap
    • (x,y) = (y,x) ;
  • 함수 파라미터를 이름대로 지정할 수 있다.
    • f(3, 2) 대신 f({value:2, key:3}) 이렇게 사용. (파라미터 이름)
    • new로 다른 계약을 만들 수 있다.

Author: crazyj7@gmail.com

'BlockChain' 카테고리의 다른 글

Solidity#2 HelloWorld  (0) 2019.12.06
Solidity 0.4 vs 0.5  (0) 2019.12.06
Windows Ethereum python module install error  (0) 2019.12.04
[ether02] 코인만들기  (0) 2019.11.10
[ether01] solidity 맛보기  (0) 2019.11.10
반응형
solidity02_helloworld

Solidity 02

  • solidity 버전 표시
pragma solidity ^0.4.25;    // 정확히 이 버전만 지원
pragma solidity >=0.4.0 <0.6.0;  // 지원 범위

  • 파일 import
import "filename";
import "filename" as symbolName ;
import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol" as it_mapping;

github에 있는 소스도 사용할 수 있다.

  • 주석은 c 형식 사용. /**/ // 등
  • public 함수나 변수는 외부에 노출
  • 반대는 internal로 표시한다. 내부에서만 호출 가능.
  • 파리미터에 memory는 라이프사이클이 함수내.
  • 파리미터에 storage로 주면 참조 형식으로 값이 변할 수 있다.
  • 함수에 view를 주면 storage 변수에 읽기 접근만 가능하다. 이벤트 발생 안된다.
  • 함수에 pure를 주면 storage 변수에 접근이 안된다.
  • view, pure를 귀찮게 왜 쓰나? gas 비용 절감과 보안측면 이다.

구버전

pragma solidity ^0.4.25 ;
contract HelloWorld {
	string public greeting ;
	function HelloWorld(string _g) public {
		greeting = _g ;
	}
	function setGreeting(string _g) public {
		greeting = _g ;
	}
	function say() public constant returns (string) {
		return greeting ;
	}
}

위는 0.4대 버전, 아래는 0.5대 버전이다. 문법이 약간 달라졌다.
- constructor가 클래스명에서 명시적으로 constructor로 변경.
- 파라미터, 리턴 변수앞에 저장소 지정을 명시적으로. (엄격해짐)
- constant가 없어짐. view로 대체.
  • public/internal 의 위치가 타입 뒤에 가는 것이 특징. (cpp, java와 다르다.)
  • 함수 리턴 타입을 지정하는 부분이 마지막에 들어간다.

신버전

pragma solidity >0.5.0;

contract HelloWorld {
	string public greeting ;
	
	constructor(string memory g) public {
		greeting = g;
	}
	
	function setGreeting(string memory g) public {
		greeting = g;
	}
	function say() public view returns (string memory) {
		return greeting ;
	}
}

image

  • deploy시 remix에서 펼쳐서 이름을 입력해줘야 인코딩에러가 안난다.
  • setGreeting시도에 펼쳐서 값을 넣어줘야 작동되었다.

Author: crazyj7@gmail.com

'BlockChain' 카테고리의 다른 글

Solidity#3 변수와 타입  (0) 2019.12.06
Solidity 0.4 vs 0.5  (0) 2019.12.06
Windows Ethereum python module install error  (0) 2019.12.04
[ether02] 코인만들기  (0) 2019.11.10
[ether01] solidity 맛보기  (0) 2019.11.10
반응형
solidity01_version

Solidity

Truffle

npm install -g truffle

작업 폴더를 만들고, 들어가서 프로젝트 초기화

truffle init

컴파일

solc source.sol --abi --bin (컴파일 변환 결과를 출력)

전체출력을 JSON 형태로 출력 (뒤에 받을 정보를 기록)
solc source.sol --combined-json abi, asm, bin

truffle을 사용한다면 truffle compile
배포는 truffle migrate로 한다.

문법

cpp처럼 ;으로 끝난다.
주석도 cpp처럼 한다. //, /* 등

pragma solidity >= 0.4.22 <0.6.0 ;
지원하는 버전을 표시한다. 0.4.22이상 0.6 미만.
특정 버전을 지칭할 경우는 ^0.4.22 이렇게 한다.

import ‘a.sol’;
다른 파일을 include 한다.
다른 사용 방식은
import * as cs from “filename”;
import “filename” as shortname;

contract 계약명 {
}
cpp 클래스처럼 정의한다.

mapping (address => uint) balances ;

버전 4와 5와 차이

solidity는 4, 5의 버전 차이가 심하다. 그것을 알아야 빌드를 할 수 있다.

  • Low-Level 함수 호출
    • callcode 삭제
    • staticcall 추가
    • 입력 파라미터가 bytes로 통일
    • 리턴값 지원
  • 지역변수 scope
    • C처럼 scope을 사용한다.
  • 배열에 pop 메소드 추가
  • 중요한 변화
  • address payable 타입 추가
    • 기존에 address 타입에 있던 send, transfer 메소드 삭제
    • 주소를 address payable 타입으로 변환해야 사용 가능하다.
    • send, transfer는 같은 기능인데 send는 low-level함수로 예외처리가 가능하다. transfer는 트랜잭션으로 처리.
    • 주소 타입을 payable로 변환하려면,
(0x...).transfer(1 ether); // 주소 상수 뒤에 바로 사용 OK
address to = 0x...;  
address(to).transfer(1 ether); // 에러!  
address(uint160(to)).transfer(1 ether); // 두번 변환은 OK
address payable x = address(uint160(to)); // 저장할 때도 두번 변환해야 OK
- msg.sender는 address payble 타입으로 변함
- msg.value는 payable, internal 함수에서만 접근 가능
- 다른 곳에서 사용하고 싶으면, 
function msgvalue() internal returns (uint256) {  
return msg.value;  
}
  • 변수 선언을 먼저 확실하게 해주어야 함. (C code)
  • 함수의 visibility (external/public/internal) 명시.
    • (v0.4는 default public)
  • 데이터로케이션(storage(상태변수참조)/memory(함수내)/calldata(함수파라미터)) 명시.
    • (v0.4는 default로 함수파라미터는 memory/calldata, 지역변수는 storage로 자동)
  • contract 타입을 address 타입으로 형변환하여 사용.
    • 0.4에서는 contract 타입이 기본적으로 address 타입과 혼용하여 사용가능했지만 transfer, balance 등을 사용하려면 명시적으로 형변환을 해줘야 한다.
  • Contract 타입간 형변환은 상속관계만 가능.
    • 상속관계가 아닌 contract로 변환하려면 형변환을 두 번하면 가능하다. A(address(b))
  • bytesX, uintX는 사이즈가 같은 경우만 형변환이 가능
    • bytes1 c=1 ;
    • bytes2 d = bytes2( c) ; // 0x0100 (오른쪽에 0이 추가)
    • bytes1 e = bytes1(d); // 0x01 (오른쪽을 제거)
    • bytes1 a = bytes1(0x100); // 0.5.0 부터는 error
    • bytes1 b = bytes1(uint8(0x100)); // 결과는 0
    • bytes1 c = bytes1(bytes2(0x100)); // 결과는 1
  • constant 키워드 삭제. 대신 view로 사용해야 함.
  • var 타입 삭제. 명시적 필요
  • suicide 함수 삭제. selfdestruct로 대체
  • sha3 함수 삭제. keccak256로 대체
  • throw 삭제. revert, require, assert 사용
  • contract명과 동일한 이름의 함수 construct 사용 불가. constructor키워드로 대체
  • 16진수표현은 0X는 삭제. 0x만 지원

Author: crazyj7@gmail.com

'BlockChain' 카테고리의 다른 글

Solidity#3 변수와 타입  (0) 2019.12.06
Solidity#2 HelloWorld  (0) 2019.12.06
Windows Ethereum python module install error  (0) 2019.12.04
[ether02] 코인만들기  (0) 2019.11.10
[ether01] solidity 맛보기  (0) 2019.11.10
반응형
windows_ethereum_pkg_error

Windows Ethereum python module install error

ethereum python 패키지를 윈도우에 설치할 때 환경에 따라 ethash에서 alloca.h 에러가 나는데 이것을 해결하기 위한 방법이 있다.

ethash

  • ethereum 패키지를 설치하는 과정에서 pyethash 모듈을 빌드하다가 에러가 발생한다. (alloca.h 에러)
  • ethhash 소스를 받아 코드를 수정하여 설치한다.
    git clone https://github.com/ethereum/ethash
1. src/libethash/mmap_win32.c
아래 코드 추가
#pragma comment(lib, "Shell32.lib")
2. src/python/core.c
#include <alloca.h> 를
#include <malloc.h> 로 바꾼다.

pip install .
으로 설치한다.
이후에 다시 ethereum을 pip로 설치시도하면 ethash를 자꾸 새로 설치하려고 하면서 동일한 에러가 나고 롤백이 된다.

ethereum

  • ethereum 패키지 소스를 받아 의존성 수정하여 설치한다.
    https://github.com/ethereum/pyethereum/releases/tag/v2.3.2
    소스를 받아서 풀고
    requirements.txt 에서 ethash 설치하는 부분을 삭제한다. (이미 패치한것을 위에서 설치했으므로 건너뛰도록 하는 것이다.)
    pip install .
    으로 설치한다.

Author: crazyj7@gmail.com

'BlockChain' 카테고리의 다른 글

Solidity#2 HelloWorld  (0) 2019.12.06
Solidity 0.4 vs 0.5  (0) 2019.12.06
[ether02] 코인만들기  (0) 2019.11.10
[ether01] solidity 맛보기  (0) 2019.11.10
이더리움개발 환경 준비  (1) 2019.11.10
반응형
module_conflict

Python module conflict error

파이썬으로 외부의 여러 패키지들을 깔고 테스트하다 보면 가끔씩 충돌이 발생하여 이전에는 잘 되던 것들이 꼬이게 된다.
막상 경험해 보면 복구하는 것이 쉽지 않고 점점 더 꼬이는 악순환이 발생하여 나중에는 파이썬을 다시 설치하게 된다.
어떻게 복구하는 방법이 없을까?

먼저 가끔씩 현상황을 기록해 두자.

pip freeze > requirements.txt

  • 위와 같이 freeze 옵션을 사용하면 현재 설치된 모든 모듈의 버전들이 기록된다. 보통은 requirements.txt 로 많이 기록된 것을 볼 수 있다.
  • 나중에 저 목록을 한 번에 설치가 가능하다. install -r 옵션을 사용한다.

마지막에 설치/변경된 모듈들을 삭제.

  • 마지막에 설치/변경된 모듈들을 하나씩 삭제해 올라간다.
  • 그런데 마지막순으로 설치된 모듈들이 무엇인지 기억이 나지 않는다.

현재 python 환경(env)의 설치 경로들을 확인.
conda env list
python --version
코드로 라이브러리 위치 확인

import os, inspect
inspect.getfile(os)
'opt/anacoda3/lib/python3.7/os.py'

import web3
inspect.getfile(web3)
'/home/crazyj/myvenv/lib/python3.7/site-packages/web3/__init__.py'
  • 위와 같이 패키지 설치 경로를 확인한 다음 디렉터리로 가서 날짜를 확인한다.

ls -ltr : 마지막에 나온것들이 최근 설치/업데이트된 패키지들. (last modified time 기준으로 역순소팅)
위 마지막 패키지들을 pip uninstall로 하나씩 지워나가면서 테스트 한다.

모든 패키지 삭제하기

이것도 저것도 안된다면, 백업받은 패키지 목록대로 돌리기 위해 전부 삭제하고 다시 설치하자.

pip freeze | xargs pip uninstall -y
또는
pip freeze > requirements.txt
pip uninstall -r requirements.txt -y

패키지 목록 한번에 설치하기

pip install -r requirements.txt

Author: crazyj7@gmail.com

'Python' 카테고리의 다른 글

Docker python venv 패키지 유지  (0) 2020.06.07
딕셔너리에서 키삭제  (0) 2019.12.07
파이썬 개발환경/가상환경구축  (0) 2019.12.01
진법 표현 및 수 스트링 변환  (0) 2019.11.24
크롤링 BeautifulSoup 요약  (1) 2019.11.06

+ Recent posts