Coding/Python 삽질기2021. 1. 17. 23:23

인터넷 커뮤티니에서 본 모대학 수학문제를 풀어 보았다.

약간 변경해서, 1^1 + 2^2 + ... + 10000^10000 의 결과 중 끝 50자리를 출력하는 형식으로 바꿔보았다.

from multiprocessing import Pool
import time

MAX_COUNT = 10**50


def mypower(num):
    result = 1
    
    for i in range(num):
        result = result * num
        if result < MAX_COUNT:
            continue
        result = result % MAX_COUNT         
        
    return result
    

def get_sum(num):
   
   assert num > 0
   
   numbers = [i for i in range(1, num+1)]
   assert len(numbers) == num
   
   pool = Pool(processes=4)
   return sum(list(pool.map(mypower, numbers))) % MAX_COUNT
   

if __name__ == '__main__':
    start_time = time.time() 
    print(get_sum(10000))
    print(time.time() - start_time)
    
16026394753230301057223656223127837280816237204500
3.0160417556762695
Posted by chobocho
Coding/CPP 삽질기2020. 12. 6. 16:41

이진검색 설명:

ko.wikipedia.org/wiki/%EC%9D%B4%EC%A7%84_%EA%B2%80%EC%83%89_%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98

 

이진 검색 알고리즘 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 이진 검색 알고리즘(binary search algorithm)은 오름차순으로 정렬된 리스트에서 특정한 값의 위치를 찾는 알고리즘이다. 처음 중간의 값을 임의의 값으로 선택하여,

ko.wikipedia.org

구현 예제

#include <stdio.h>
#include <assert.h>


/*
 * high must be length of arr -1
 * /
int binary_search(int value, int low, int high, int* arr) {
	while (low <= high) {
		int mid = (low+high)/2;
		if (arr[mid] == value) {
			return mid;
		} else if (arr[mid] < value) {
			low = mid+1;
		} else {
			high = mid-1;
		}
	}
	return -1;
}

/*
 * high must be length of arr -1
 * /
int binary_search_recursive(int value, int low, int high, int *arr) {
	if (low > high) return -1;

	int mid = (low + high) / 2;
	if (arr[mid] == value) {
		return mid;
	} else if (arr[mid] < value) {
		return binary_search_recursive(value, mid+1, high, arr);
	} else {
		return binary_search_recursive(value, low, mid-1, arr);
	}
}

void test() {
	int number[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};

	int arr_size = (int) sizeof(number)/sizeof(int);

	assert(binary_search(11, 0, arr_size-1, number) == 11);
	assert(binary_search(2, 0, arr_size-1, number) == 2);
	assert(binary_search(12, 0, arr_size-1, number) == -1);
	
	assert(binary_search_recursive(11, 0, arr_size-1, number) == 11);
	assert(binary_search_recursive(2, 0, arr_size-1, number) == 2);
	assert(binary_search_recursive(12, 0, arr_size-1, number) == -1);
}

int main(int argc, char **argv) {
    test();
    return 0;
}

 

'Coding > CPP 삽질기' 카테고리의 다른 글

Stack과 Heap  (0) 2021.02.25
Quick sort  (0) 2017.07.13
Bit 연산 정리  (0) 2016.08.20
Posted by chobocho
Coding/Python 삽질기2020. 10. 28. 22:32
Posted by chobocho
Coding/JavsScript 삽질기2020. 9. 23. 23:04

자바스크립트로 테트리스를 만들어 보았습니다.

1) Play 해보기 (크롬만 지원합니다.)

사용키 : 방향키, 스페이스 (블록 아래로 내리기), Ctrl (Hold), S (Start / Resume), P (Pause)

www.chobocho.com/game/tetris/tetris.html

 

Chobocho's Tetris

 

www.chobocho.com

2) Source code

github.com/chobocho/JsTetris/tree/master/src/app/src/main/assets

 

chobocho/JsTetris

Javascript tetris. Contribute to chobocho/JsTetris development by creating an account on GitHub.

github.com

3) UML

Javascript Tetris UML

Posted by chobocho
Coding/Script2020. 9. 10. 23:55

'Coding > Script' 카테고리의 다른 글

[DOS] Batch 파일  (0) 2023.09.07
windows 에서 pop띄우기  (0) 2017.06.15
[Excel VBA] File open / 파일열기  (0) 2016.12.20
Posted by chobocho
Coding/JavsScript 삽질기2020. 9. 10. 01:40

자바스크립트를 이용하여 테트리스를 만들고, 이를 Android의 WebView를 이용하여 Android 앱으로 만들어 보았다.

소스코드: github.com/chobocho/JsTetris

 

chobocho/JsTetris

Javascript tetris. Contribute to chobocho/JsTetris development by creating an account on GitHub.

github.com

다운로드: play.google.com/store/apps/details?id=com.chobocho.jstetris

 

Classic Block Game V2 - Google Play 앱

Simple block game

play.google.com

웹 브라우저로 해보기 (크롬에서만 동작 확인을 했습니다)

www.chobocho.com/game/tetris/tetris.html

 

Chobocho's Tetris

 

www.chobocho.com

* 사용키 : 방향키, 스페이스 (블록 아래로 내리기), Ctrl (Hold), S (Start / Resume), P (Pause)

 

Posted by chobocho
Coding/Python 삽질기2020. 8. 25. 23:00

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] 폴더 안의 파일 이름 검색하기  (0) 2020.10.28
[Python][AI] XOR 예제  (0) 2020.08.03
[Python][AI] Perceptron 예제  (0) 2020.07.28
Posted by chobocho
Coding/Python 삽질기2020. 8. 3. 22:33

아래와 같이 1개의 은닉층을 가진 신경망을 구성해 보았습니다.

 

import numpy as np

def sigmoid(x):
    return 1/(1+np.exp(-x))


def DeltaSGD(W1, W2, X, D):
    alpha = 0.9
    
    idx = 0
    for k in X:
        a1 = np.dot(W1, k)
        z1 = sigmoid(a1)
        
        a2 = np.dot(W2, z1)
        y = sigmoid(a2)
        
        e = D[idx] - y
        delta = y * (1-y) * e
        
        e1 = W2 * delta
        delta1 = z1 * (1-z1) * e1

        dw1 = alpha * delta1
        dw1 = dw1.reshape(4,1)
        x = k.reshape(1,3)
        W1 += np.dot(dw1, x)
        
        dw2 = alpha * delta * z1
        W2 += dw2
        idx+=1

        
def Train(epoch, x, y, W1, W2):
    for ep in range (epoch):
        DeltaSGD(W1, W2, x, y)

        
def main():
    W1 = np.random.randn(4,3)
    W2 = np.random.randn(4)
    x = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
    y = np.array([0, 1, 1, 0])
    trainCount = 10000

    print('---Before Training---')
    print(W1)
    print(W2)
    print('---After Training---')
    Train(trainCount, x, y, W1, W2)
    print(W1)
    print(W2)
    
    print('---Result---')
    for k in x:
        a1 = np.dot(W1, k)
        z1 = sigmoid(a1)
        
        a2 = np.dot(W2, z1)
        y = sigmoid(a2)
        print(y) 
        
        
if __name__ == '__main__':       
    main()        
---Before Training---
[[-0.82542712 -0.65157477  0.09131077]
 [-0.12367401  1.07601221 -1.43941252]
 [-1.00401084 -0.04547823  0.97194216]
 [ 0.02719329 -0.22932678 -0.45809196]]
[ 0.16840571 -0.55206913  1.75255171 -0.54203599]
---After Training---
[[-6.3608461  -6.35976778  2.71126418]
 [ 3.61918383  3.62562196 -5.65337702]
 [-3.70117648 -3.70158904  5.76910815]
 [-1.51981715 -1.56682777 -0.58710802]]
[-11.12882426  -6.71646542   6.50908732  -1.52377049]
---Result---
0.01083108954199271
0.9896067125952175
0.9895881791368779
0.01040259419256147

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Pygame] Paper Plane Game 만들기  (0) 2020.08.25
[Python][AI] Perceptron 예제  (0) 2020.07.28
[Python] fisher-yates shuffle  (0) 2020.07.20
Posted by chobocho
Coding/Python 삽질기2020. 7. 28. 23:56

 

import numpy as np

def sigmoid(x):
    return 1/(1+np.exp(-x))


def DeltaSGD(W, X, D):
    alpha = 0.9
    dwSum = np.array([0] * 3)
    
    idx = 0
    for k in X:
        a1 = np.dot(k, W)
        y = sigmoid(a1)
        
        e = D[idx] - y
        delta = y * (1-y) * e
        
        dw = alpha * delta * k
        W += dw
        idx+=1

        
def Train(epoch, x, y, W1):
    for ep in range (epoch):
        DeltaSGD(W1, x, y)

        
def main():
    W1 = np.random.randn(3)
    x = np.array([[0, 0, 1], [0, 1, 1], [1, 1, 1], [1, 0, 0]])
    y = np.array([1, 1, 1, 0])

    Train(10000, x, y, W1)
    
    for k in x:
        a1 = np.dot(k, W1)
        z1 = sigmoid(a1)
        print(z1)    
        
        
if __name__ == '__main__':       
    main()  

 

0.9962960119369554
0.9999259998523653
0.9929612087250037
0.010332095384834877

'Coding > Python 삽질기' 카테고리의 다른 글

[Python][AI] XOR 예제  (0) 2020.08.03
[Python] fisher-yates shuffle  (0) 2020.07.20
강아지 나이 계산기  (0) 2020.07.16
Posted by chobocho
Coding/Python 삽질기2020. 7. 20. 23:27
import random

number = [1, 2, 3, 4, 5, 7, 8]

def shuffle(number):
   for i in range (len(number)-1, 0, -1):
       j = random.randint(0, i)
       number[j], number[i] = number[i], number[j]
    
shuffle(number)

 동작을 보면 아래와 같이 변화 한다

[1, 2, 3, 4, 5, 7, 8]
[1, 8, 3, 4, 5, 7, 2]
[1, 8, 3, 4, 5, 7, 2]
[1, 8, 3, 4, 5, 7, 2]
[1, 8, 3, 4, 5, 7, 2]
[3, 8, 1, 4, 5, 7, 2]
[3, 8, 1, 4, 5, 7, 2]

* 참고: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

'Coding > Python 삽질기' 카테고리의 다른 글

[Python][AI] Perceptron 예제  (0) 2020.07.28
강아지 나이 계산기  (0) 2020.07.16
[Python] 소인수 분해  (0) 2020.07.10
Posted by chobocho